import os
import pytest
import yaml

from photoshell.selection import Selection

@pytest.fixture
def sidecar(tmpdir):
    tmpdir.join("test.sidecar").write(yaml.dump({
        'developed_path': os.path.join(tmpdir.strpath, "test.jpeg"),
        'datetime': '2014-10-10 00:00'
    }, default_flow_style=False))
    return os.path.join(tmpdir.strpath, "test.sidecar")

@pytest.fixture
def empty_selection():
    s = Selection('', '')
    return s

@pytest.fixture
def selection(empty_selection):
    empty_selection.images.append('image')
    empty_selection.photos.append('image')
    return empty_selection

def test_current_default_selection(selection):
    assert selection.current()

def test_current_is_none_if_selection_empty(empty_selection):
    assert empty_selection.current() is None

def test_current_photo_default_selection(selection):
    assert selection.current_photo()

def test_current_photo_is_none_if_selection_empty(empty_selection):
    assert empty_selection.current_photo() is None

def test_next_prev_does_nothing_single_photo(selection):
    assert selection.current() == selection.next()
    assert selection.current() == selection.prev()

def test_next_prev_wrap_around(selection):
    selection.photos.append('photo2')
    selection.images.append('image2')

    assert selection.next() == 'image2'
    assert selection.next() == 'image'
    assert selection.prev() == 'image2'
    assert selection.prev() == 'image'

Add a few behavior tests for selection

Add a few behavior tests for selection

Response:
<INSERT> import os
import pytest
import yaml

from photoshell.selection import Selection

@pytest.fixture
def sidecar(tmpdir):
 <INSERT_END> <INSERT>   tmpdir.join("test.sidecar").write(yaml.dump({
        'developed_path': os.path.join(tmpdir.strpath, "test.jpeg"),
        'datetime': '2014-10-10 00:00'
    }, default_flow_style=False))
    return os.path.join(tmpdir.strpath, "test.sidecar")

@pytest.fixture
def empty_selection():
    s = Selection('', '')
    return s

@pytest.fixture
def selection(empty_selection):
    empty_selection.images.append('image')
    empty_selection.photos.append('image')
    return empty_selection

def test_current_default_selection(selection):
    assert selection.current()

def test_current_is_none_if_selection_empty(empty_selection):
    assert empty_selection.current() is None

def test_current_photo_default_selection(selection):
    assert selection.current_photo()

def test_current_photo_is_none_if_selection_empty(empty_selection):
    assert empty_selection.current_photo() is None

def test_next_prev_does_nothing_single_photo(selection):
    assert selection.current() == selection.next()
    assert selection.current() == selection.prev()

def test_next_prev_wrap_around(selection):
    selection.photos.append('photo2')
    selection.images.append('image2')

    assert selection.next() == 'image2'
    assert selection.next() == 'image'
    assert selection.prev() == 'image2'
    assert selection.prev() == 'image'
 <INSERT_END> <|endoftext|> import os
import pytest
import yaml

from photoshell.selection import Selection

@pytest.fixture
def sidecar(tmpdir):
    tmpdir.join("test.sidecar").write(yaml.dump({
        'developed_path': os.path.join(tmpdir.strpath, "test.jpeg"),
        'datetime': '2014-10-10 00:00'
    }, default_flow_style=False))
    return os.path.join(tmpdir.strpath, "test.sidecar")

@pytest.fixture
def empty_selection():
    s = Selection('', '')
    return s

@pytest.fixture
def selection(empty_selection):
    empty_selection.images.append('image')
    empty_selection.photos.append('image')
    return empty_selection

def test_current_default_selection(selection):
    assert selection.current()

def test_current_is_none_if_selection_empty(empty_selection):
    assert empty_selection.current() is None

def test_current_photo_default_selection(selection):
    assert selection.current_photo()

def test_current_photo_is_none_if_selection_empty(empty_selection):
    assert empty_selection.current_photo() is None

def test_next_prev_does_nothing_single_photo(selection):
    assert selection.current() == selection.next()
    assert selection.current() == selection.prev()

def test_next_prev_wrap_around(selection):
    selection.photos.append('photo2')
    selection.images.append('image2')

    assert selection.next() == 'image2'
    assert selection.next() == 'image'
    assert selection.prev() == 'image2'
    assert selection.prev() == 'image'

Prompt: Add a few behavior tests for selection


import pytz
from datetime import datetime, timedelta
from django.test import TestCase

from api.factories import TopicFactory
from rest_framework.test import APIRequestFactory, force_authenticate
from api.factories import UserFactory
from api.serializers import TopicSerializer
from api.views.topics import TopicViewSet

class TopicAPITest(TestCase):
    def setUp(self):
        self.factory = APIRequestFactory()
        self.active_view = TopicViewSet.as_view({'get': 'active'})
        self.inactive_view = TopicViewSet.as_view({'get': 'inactive'})
        self.user = UserFactory()

        self.active_topics_count = 5
        self.inactive_topics_count = 5

        TopicFactory.create_batch(self.active_topics_count, start=datetime.now(pytz.utc) - timedelta(days=3),
                                  end=datetime.now(pytz.utc) + timedelta(days=4))
        TopicFactory.create_batch(self.inactive_topics_count, start=datetime.now(pytz.utc) + timedelta(weeks=1),
                                  end=datetime.now(pytz.utc) + timedelta(weeks=2))

    def test_active_topics_are_returned_correctly(self):
        request = self.factory.get("api/topics/active")
        force_authenticate(request, user=self.user)
        response = self.active_view(request)
        topics = TopicSerializer(data=response.data, many=True)
        topics.is_valid(raise_exception=True)
        topics = topics.create(topics.validated_data)

        self.assertEqual(self.active_topics_count, len(topics))

        for topic in topics:
            self.assertTrue(topic.is_active())

    def test_inactive_topics_are_returned_correctly(self):
        request = self.factory.get("api/topics/inactive")
        force_authenticate(request, user=self.user)
        response = self.inactive_view(request)
        topics = TopicSerializer(data=response.data, many=True)
        topics.is_valid(raise_exception=True)
        topics = topics.create(topics.validated_data)

        self.assertEqual(self.inactive_topics_count, len(topics))

        for topic in topics:
            self.assertFalse(topic.is_active())

Write tests for active and inactive list routes

Response:
<REPLACE_OLD>  <REPLACE_NEW> import pytz
from datetime import datetime, timedelta
from django.test import TestCase

from api.factories import TopicFactory
from rest_framework.test import APIRequestFactory, force_authenticate
from api.factories import UserFactory
from api.serializers import TopicSerializer
from api.views.topics import TopicViewSet

class TopicAPITest(TestCase):
    def setUp(self):
        self.factory = APIRequestFactory()
        self.active_view = TopicViewSet.as_view({'get': 'active'})
        self.inactive_view = TopicViewSet.as_view({'get': 'inactive'})
        self.user = UserFactory()

        self.active_topics_count = 5
        self.inactive_topics_count = 5

        TopicFactory.create_batch(self.active_topics_count, start=datetime.now(pytz.utc) - timedelta(days=3),
                                  end=datetime.now(pytz.utc) + timedelta(days=4))
        TopicFactory.create_batch(self.inactive_topics_count, start=datetime.now(pytz.utc) + timedelta(weeks=1),
                                  end=datetime.now(pytz.utc) + timedelta(weeks=2))

    def test_active_topics_are_returned_correctly(self):
        request = self.factory.get("api/topics/active")
        force_authenticate(request, user=self.user)
        response = self.active_view(request)
        topics = TopicSerializer(data=response.data, many=True)
        topics.is_valid(raise_exception=True)
        topics = topics.create(topics.validated_data)

        self.assertEqual(self.active_topics_count, len(topics))

        for topic in topics:
            self.assertTrue(topic.is_active())

    def test_inactive_topics_are_returned_correctly(self):
        request = self.factory.get("api/topics/inactive")
        force_authenticate(request, user=self.user)
        response = self.inactive_view(request)
        topics = TopicSerializer(data=response.data, many=True)
        topics.is_valid(raise_exception=True)
        topics = topics.create(topics.validated_data)

        self.assertEqual(self.inactive_topics_count, len(topics))

        for topic in topics:
            self.assertFalse(topic.is_active())
 <REPLACE_END> <|endoftext|> import pytz
from datetime import datetime, timedelta
from django.test import TestCase

from api.factories import TopicFactory
from rest_framework.test import APIRequestFactory, force_authenticate
from api.factories import UserFactory
from api.serializers import TopicSerializer
from api.views.topics import TopicViewSet

class TopicAPITest(TestCase):
    def setUp(self):
        self.factory = APIRequestFactory()
        self.active_view = TopicViewSet.as_view({'get': 'active'})
        self.inactive_view = TopicViewSet.as_view({'get': 'inactive'})
        self.user = UserFactory()

        self.active_topics_count = 5
        self.inactive_topics_count = 5

        TopicFactory.create_batch(self.active_topics_count, start=datetime.now(pytz.utc) - timedelta(days=3),
                                  end=datetime.now(pytz.utc) + timedelta(days=4))
        TopicFactory.create_batch(self.inactive_topics_count, start=datetime.now(pytz.utc) + timedelta(weeks=1),
                                  end=datetime.now(pytz.utc) + timedelta(weeks=2))

    def test_active_topics_are_returned_correctly(self):
        request = self.factory.get("api/topics/active")
        force_authenticate(request, user=self.user)
        response = self.active_view(request)
        topics = TopicSerializer(data=response.data, many=True)
        topics.is_valid(raise_exception=True)
        topics = topics.create(topics.validated_data)

        self.assertEqual(self.active_topics_count, len(topics))

        for topic in topics:
            self.assertTrue(topic.is_active())

    def test_inactive_topics_are_returned_correctly(self):
        request = self.factory.get("api/topics/inactive")
        force_authenticate(request, user=self.user)
        response = self.inactive_view(request)
        topics = TopicSerializer(data=response.data, many=True)
        topics.is_valid(raise_exception=True)
        topics = topics.create(topics.validated_data)

        self.assertEqual(self.inactive_topics_count, len(topics))

        for topic in topics:
            self.assertFalse(topic.is_active())

Prompt: Write tests for active and inactive list routes


from unittest import TestCase

from pydatajson.threading_helper import apply_threading

class ThreadingTests(TestCase):

    def test_threading(self):
        elements = [1, 2, 3, 4]

        def function(x):
            return x ** 2

        result = apply_threading(elements, function, 3)

        self.assertEqual(result, [1, 4, 9, 16])

Test case que pase por threading

Test case que pase por threading

Response:
<INSERT> from unittest import TestCase

from pydatajson.threading_helper import apply_threading

class ThreadingTests(TestCase):

 <INSERT_END> <INSERT>   def test_threading(self):
        elements = [1, 2, 3, 4]

        def function(x):
            return x ** 2

        result = apply_threading(elements, function, 3)

        self.assertEqual(result, [1, 4, 9, 16])
 <INSERT_END> <|endoftext|> from unittest import TestCase

from pydatajson.threading_helper import apply_threading

class ThreadingTests(TestCase):

    def test_threading(self):
        elements = [1, 2, 3, 4]

        def function(x):
            return x ** 2

        result = apply_threading(elements, function, 3)

        self.assertEqual(result, [1, 4, 9, 16])

Prompt: Test case que pase por threading


"""
Implementation of Thompson sampling for continuous spaces.
"""

from __future__ import division
from __future__ import absolute_import
from __future__ import print_function

from collections import deque
from ..utils import params

__all__ = ['Thompson']

@params('n')
def Thompson(model, n=100, rng=None):
    """
    Implementation of Thompson sampling for continuous models using a finite
    approximation to the kernel matrix with `n` Fourier components.
    """
    if hasattr(model, '__iter__'):
        model = deque(model, maxlen=1).pop()
    return model.sample_fourier(n, rng).get

Response:
<REPLACE_OLD> """
Acquisition functions based on (GP) UCB.
"""

# future imports
from <REPLACE_NEW> """
Implementation of Thompson sampling for continuous spaces.
"""

from <REPLACE_END> <REPLACE_OLD> print_function

# use this to simplify (slightly) the Thompson implementation with sampled
# models.
from <REPLACE_NEW> print_function

from <REPLACE_END> <REPLACE_OLD> deque

# local imports
from <REPLACE_NEW> deque
from <REPLACE_END> <REPLACE_OLD> params

# exported symbols
__all__ <REPLACE_NEW> params

__all__ <REPLACE_END> <REPLACE_OLD> n=100):
 <REPLACE_NEW> n=100, rng=None):
 <REPLACE_END> <REPLACE_OLD> model.sample_fourier(n).get
 <REPLACE_NEW> model.sample_fourier(n, rng).get
 <REPLACE_END> <|endoftext|> """
Implementation of Thompson sampling for continuous spaces.
"""

from __future__ import division
from __future__ import absolute_import
from __future__ import print_function

from collections import deque
from ..utils import params

__all__ = ['Thompson']

@params('n')
def Thompson(model, n=100, rng=None):
    """
    Implementation of Thompson sampling for continuous models using a finite
    approximation to the kernel matrix with `n` Fourier components.
    """
    if hasattr(model, '__iter__'):
        model = deque(model, maxlen=1).pop()
    return model.sample_fourier(n, rng).get

Prompt:
Fix Thompson to pay attention to the RNG.

"""
Acquisition functions based on (GP) UCB.
"""

# future imports
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function

# use this to simplify (slightly) the Thompson implementation with sampled
# models.
from collections import deque

# local imports
from ..utils import params

# exported symbols
__all__ = ['Thompson']

@params('n')
def Thompson(model, n=100):
    """
    Implementation of Thompson sampling for continuous models using a finite
    approximation to the kernel matrix with `n` Fourier components.
    """
    if hasattr(model, '__iter__'):
        model = deque(model, maxlen=1).pop()
    return model.sample_fourier(n).get


from test_support import verbose, findfile, TestFailed, TestSkipped
import linuxaudiodev
import errno
import os

def play_sound_file(path):
    fp = open(path, 'r')
    data = fp.read()
    fp.close()
    try:
        a = linuxaudiodev.open('w')
    except linuxaudiodev.error, msg:
	if msg[0] in (errno.EACCES, errno.ENODEV):
		raise TestSkipped, msg
        raise TestFailed, msg
    else:
        a.write(data)
        a.close()

def test():
    play_sound_file(findfile('audiotest.au'))

test()

Response:
<REPLACE_OLD> TestFailed
import <REPLACE_NEW> TestFailed, TestSkipped
import <REPLACE_END> <REPLACE_OLD> ImportError, <REPLACE_NEW> TestSkipped, <REPLACE_END> <|endoftext|> from test_support import verbose, findfile, TestFailed, TestSkipped
import linuxaudiodev
import errno
import os

def play_sound_file(path):
    fp = open(path, 'r')
    data = fp.read()
    fp.close()
    try:
        a = linuxaudiodev.open('w')
    except linuxaudiodev.error, msg:
	if msg[0] in (errno.EACCES, errno.ENODEV):
		raise TestSkipped, msg
        raise TestFailed, msg
    else:
        a.write(data)
        a.close()

def test():
    play_sound_file(findfile('audiotest.au'))

test()

Prompt:
Raise TestSkipped, not ImportError.
Honesty's the best policy.

from test_support import verbose, findfile, TestFailed
import linuxaudiodev
import errno
import os

def play_sound_file(path):
    fp = open(path, 'r')
    data = fp.read()
    fp.close()
    try:
        a = linuxaudiodev.open('w')
    except linuxaudiodev.error, msg:
	if msg[0] in (errno.EACCES, errno.ENODEV):
		raise ImportError, msg
        raise TestFailed, msg
    else:
        a.write(data)
        a.close()

def test():
    play_sound_file(findfile('audiotest.au'))

test()


# Generated by Django 4.0.5 on 2022-06-22 05:40

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ("services", "0096_create_syllables_fi_columns"),
    ]

    operations = [
        migrations.AlterField(
            model_name="unitconnection",
            name="section_type",
            field=models.PositiveSmallIntegerField(
                choices=[
                    (1, "PHONE_OR_EMAIL"),
                    (2, "LINK"),
                    (3, "TOPICAL"),
                    (4, "OTHER_INFO"),
                    (5, "OPENING_HOURS"),
                    (6, "SOCIAL_MEDIA_LINK"),
                    (7, "OTHER_ADDRESS"),
                    (8, "HIGHLIGHT"),
                    (9, "ESERVICE_LINK"),
                    (10, "PRICE"),
                    (11, "SUBGROUP"),
                ],
                null=True,
            ),
        ),
    ]

Add migration for unitconnection section types

Response:
<REPLACE_OLD>  <REPLACE_NEW> # Generated by Django 4.0.5 on 2022-06-22 05:40

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ("services", "0096_create_syllables_fi_columns"),
    ]

    operations = [
        migrations.AlterField(
            model_name="unitconnection",
            name="section_type",
            field=models.PositiveSmallIntegerField(
                choices=[
                    (1, "PHONE_OR_EMAIL"),
                    (2, "LINK"),
                    (3, "TOPICAL"),
                    (4, "OTHER_INFO"),
                    (5, "OPENING_HOURS"),
                    (6, "SOCIAL_MEDIA_LINK"),
                    (7, "OTHER_ADDRESS"),
                    (8, "HIGHLIGHT"),
                    (9, "ESERVICE_LINK"),
                    (10, "PRICE"),
                    (11, "SUBGROUP"),
                ],
                null=True,
            ),
        ),
    ]
 <REPLACE_END> <|endoftext|> # Generated by Django 4.0.5 on 2022-06-22 05:40

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ("services", "0096_create_syllables_fi_columns"),
    ]

    operations = [
        migrations.AlterField(
            model_name="unitconnection",
            name="section_type",
            field=models.PositiveSmallIntegerField(
                choices=[
                    (1, "PHONE_OR_EMAIL"),
                    (2, "LINK"),
                    (3, "TOPICAL"),
                    (4, "OTHER_INFO"),
                    (5, "OPENING_HOURS"),
                    (6, "SOCIAL_MEDIA_LINK"),
                    (7, "OTHER_ADDRESS"),
                    (8, "HIGHLIGHT"),
                    (9, "ESERVICE_LINK"),
                    (10, "PRICE"),
                    (11, "SUBGROUP"),
                ],
                null=True,
            ),
        ),
    ]

Prompt: Add migration for unitconnection section types


import tomviz.operators

NUMBER_OF_CHUNKS = 10

class InvertOperator(tomviz.operators.CancelableOperator):

    def transform_scalars(self, dataset):
        from tomviz import utils
        import numpy as np
        self.progress.maximum = NUMBER_OF_CHUNKS

        scalars = utils.get_scalars(dataset)
        if scalars is None:
            raise RuntimeError("No scalars found!")

        result = np.float32(scalars)
        min = np.amin(scalars)
        max = np.amax(scalars)
        step = 0
        for chunk in np.array_split(result, NUMBER_OF_CHUNKS):
            if self.canceled:
                return
            chunk[:] = max - chunk + min
            step += 1
            self.progress.value = step

        utils.set_scalars(dataset, result)

Response:
<INSERT>        min = np.amin(scalars)
 <INSERT_END> <REPLACE_OLD> chunk
 <REPLACE_NEW> chunk + min
 <REPLACE_END> <|endoftext|> import tomviz.operators

NUMBER_OF_CHUNKS = 10

class InvertOperator(tomviz.operators.CancelableOperator):

    def transform_scalars(self, dataset):
        from tomviz import utils
        import numpy as np
        self.progress.maximum = NUMBER_OF_CHUNKS

        scalars = utils.get_scalars(dataset)
        if scalars is None:
            raise RuntimeError("No scalars found!")

        result = np.float32(scalars)
        min = np.amin(scalars)
        max = np.amax(scalars)
        step = 0
        for chunk in np.array_split(result, NUMBER_OF_CHUNKS):
            if self.canceled:
                return
            chunk[:] = max - chunk + min
            step += 1
            self.progress.value = step

        utils.set_scalars(dataset, result)

Prompt:
Add the minimum scalar value to the result of the InvertOperator

Without it, all results would be shifted so the minimum was 0.

import tomviz.operators

NUMBER_OF_CHUNKS = 10

class InvertOperator(tomviz.operators.CancelableOperator):

    def transform_scalars(self, dataset):
        from tomviz import utils
        import numpy as np
        self.progress.maximum = NUMBER_OF_CHUNKS

        scalars = utils.get_scalars(dataset)
        if scalars is None:
            raise RuntimeError("No scalars found!")

        result = np.float32(scalars)
        max = np.amax(scalars)
        step = 0
        for chunk in np.array_split(result, NUMBER_OF_CHUNKS):
            if self.canceled:
                return
            chunk[:] = max - chunk
            step += 1
            self.progress.value = step

        utils.set_scalars(dataset, result)


Add a missing line between imports

Add a missing line between imports

Response:
<REPLACE_OLD> views

urlpatterns <REPLACE_NEW> views

urlpatterns <REPLACE_END> <|endoftext|> from django.conf import settings
from django.conf.urls import url
from django.http import HttpResponse
from django.views import generic

from . import views

urlpatterns = (
    url(r'^robots\.txt$', views.RobotsView.as_view(), name="robots"),
)

if getattr(settings, 'LOADERIO_TOKEN', None):
    loaderio_token = settings.LOADERIO_TOKEN

    class LoaderioTokenView(generic.View):
        def get(self, request, *args, **kwargs):
            return HttpResponse('{}'.format(loaderio_token))

    urlpatterns += (
        url(r'^{}/$'.format(loaderio_token), LoaderioTokenView.as_view()),
    )

Prompt:
Add a missing line between imports

from django.conf import settings
from django.conf.urls import url
from django.http import HttpResponse
from django.views import generic

from . import views

urlpatterns = (
    url(r'^robots\.txt$', views.RobotsView.as_view(), name="robots"),
)

if getattr(settings, 'LOADERIO_TOKEN', None):
    loaderio_token = settings.LOADERIO_TOKEN

    class LoaderioTokenView(generic.View):
        def get(self, request, *args, **kwargs):
            return HttpResponse('{}'.format(loaderio_token))

    urlpatterns += (
        url(r'^{}/$'.format(loaderio_token), LoaderioTokenView.as_view()),
    )


import math

def line_magnitude (x1, y1, x2, y2):
    return math.sqrt(math.pow((x2 - x1), 2) + math.pow((y2 - y1), 2))

#Calc minimum distance from a point and a line segment (i.e. consecutive vertices in a polyline).
def distance_point_line (px, py, x1, y1, x2, y2):
    #http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/source.vba
    LineMag = line_magnitude(x1, y1, x2, y2)

    if LineMag < 0.00000001:
        dpl = 9999
        return dpl

    u1 = (((px - x1) * (x2 - x1)) + ((py - y1) * (y2 - y1)))
    u = u1 / (LineMag * LineMag)

    if (u < 0.00001) or (u > 1):
        #// closest point does not fall within the line segment, take the shorter distance
        #// to an endpoint
        ix = line_magnitude(px, py, x1, y1)
        iy = line_magnitude(px, py, x2, y2)
        if ix > iy:
            dpl = iy
        else:
            dpl = ix
    else:
        # Intersecting point is on the line, use the formula
        ix = x1 + u * (x2 - x1)
        iy = y1 + u * (y2 - y1)
        dpl = line_magnitude(px, py, ix, iy)

    return dpl

Move geometric functions into a separate file

Response:
<REPLACE_OLD>  <REPLACE_NEW> import math

def line_magnitude (x1, y1, x2, y2):
    return math.sqrt(math.pow((x2 - x1), 2) + math.pow((y2 - y1), 2))

#Calc minimum distance from a point and a line segment (i.e. consecutive vertices in a polyline).
def distance_point_line (px, py, x1, y1, x2, y2):
    #http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/source.vba
    LineMag = line_magnitude(x1, y1, x2, y2)

    if LineMag < 0.00000001:
        dpl = 9999
        return dpl

    u1 = (((px - x1) * (x2 - x1)) + ((py - y1) * (y2 - y1)))
    u = u1 / (LineMag * LineMag)

    if (u < 0.00001) or (u > 1):
        #// closest point does not fall within the line segment, take the shorter distance
        #// to an endpoint
        ix = line_magnitude(px, py, x1, y1)
        iy = line_magnitude(px, py, x2, y2)
        if ix > iy:
            dpl = iy
        else:
            dpl = ix
    else:
        # Intersecting point is on the line, use the formula
        ix = x1 + u * (x2 - x1)
        iy = y1 + u * (y2 - y1)
        dpl = line_magnitude(px, py, ix, iy)

    return dpl
 <REPLACE_END> <|endoftext|> import math

def line_magnitude (x1, y1, x2, y2):
    return math.sqrt(math.pow((x2 - x1), 2) + math.pow((y2 - y1), 2))

#Calc minimum distance from a point and a line segment (i.e. consecutive vertices in a polyline).
def distance_point_line (px, py, x1, y1, x2, y2):
    #http://local.wasp.uwa.edu.au/~pbourke/geometry/pointline/source.vba
    LineMag = line_magnitude(x1, y1, x2, y2)

    if LineMag < 0.00000001:
        dpl = 9999
        return dpl

    u1 = (((px - x1) * (x2 - x1)) + ((py - y1) * (y2 - y1)))
    u = u1 / (LineMag * LineMag)

    if (u < 0.00001) or (u > 1):
        #// closest point does not fall within the line segment, take the shorter distance
        #// to an endpoint
        ix = line_magnitude(px, py, x1, y1)
        iy = line_magnitude(px, py, x2, y2)
        if ix > iy:
            dpl = iy
        else:
            dpl = ix
    else:
        # Intersecting point is on the line, use the formula
        ix = x1 + u * (x2 - x1)
        iy = y1 + u * (y2 - y1)
        dpl = line_magnitude(px, py, ix, iy)

    return dpl

Prompt: Move geometric functions into a separate file


"""
=============
LineAnimator
=============

This example shows off some ways in which you can use the
LineAnimator object to animate line plots.
"""
import numpy as np
import matplotlib.pyplot as plt

from sunpy.visualization.animator import LineAnimator

###############################################################################
# Animate a 2D cube of random data as a line plot along an
# axis where the x-axis drifts with time.

# Define some random data
data_shape0 = (10, 20)
data0 = np.random.rand(*data_shape0)

###############################################################################
# Define the axis that will make up the line plot
plot_axis0 = 1
slider_axis0 = 0

###############################################################################
# Define value along x axis which drift with time.  To do this, define
# xdata to be the same shape as the data where each row/column
# (depending on axis to be animated) represents the x-axis values for
# a single frame of the animations.
xdata = np.tile(np.linspace(0, 100, (data_shape0[plot_axis0]+1)), (data_shape0[slider_axis0], 1))

###############################################################################
# Generate animation object with variable x-axis data.
ani = LineAnimator(data0, plot_axis_index=plot_axis0, axis_ranges=[None, xdata])

###############################################################################
# Show plot
plt.show()

Response:
<REPLACE_OLD> data_shape0[plot_axis0]), <REPLACE_NEW> (data_shape0[plot_axis0]+1)), <REPLACE_END> <|endoftext|> """
=============
LineAnimator
=============

This example shows off some ways in which you can use the
LineAnimator object to animate line plots.
"""
import numpy as np
import matplotlib.pyplot as plt

from sunpy.visualization.animator import LineAnimator

###############################################################################
# Animate a 2D cube of random data as a line plot along an
# axis where the x-axis drifts with time.

# Define some random data
data_shape0 = (10, 20)
data0 = np.random.rand(*data_shape0)

###############################################################################
# Define the axis that will make up the line plot
plot_axis0 = 1
slider_axis0 = 0

###############################################################################
# Define value along x axis which drift with time.  To do this, define
# xdata to be the same shape as the data where each row/column
# (depending on axis to be animated) represents the x-axis values for
# a single frame of the animations.
xdata = np.tile(np.linspace(0, 100, (data_shape0[plot_axis0]+1)), (data_shape0[slider_axis0], 1))

###############################################################################
# Generate animation object with variable x-axis data.
ani = LineAnimator(data0, plot_axis_index=plot_axis0, axis_ranges=[None, xdata])

###############################################################################
# Show plot
plt.show()

Prompt:
Fix LineAnimator example to adhere to new pixel edges axis_ranges API.

"""
=============
LineAnimator
=============

This example shows off some ways in which you can use the
LineAnimator object to animate line plots.
"""
import numpy as np
import matplotlib.pyplot as plt

from sunpy.visualization.animator import LineAnimator

###############################################################################
# Animate a 2D cube of random data as a line plot along an
# axis where the x-axis drifts with time.

# Define some random data
data_shape0 = (10, 20)
data0 = np.random.rand(*data_shape0)

###############################################################################
# Define the axis that will make up the line plot
plot_axis0 = 1
slider_axis0 = 0

###############################################################################
# Define value along x axis which drift with time.  To do this, define
# xdata to be the same shape as the data where each row/column
# (depending on axis to be animated) represents the x-axis values for
# a single frame of the animations.
xdata = np.tile(np.linspace(0, 100, data_shape0[plot_axis0]), (data_shape0[slider_axis0], 1))

###############################################################################
# Generate animation object with variable x-axis data.
ani = LineAnimator(data0, plot_axis_index=plot_axis0, axis_ranges=[None, xdata])

###############################################################################
# Show plot
plt.show()


#!/usr/bin/env python
import re, sys, os
if len(sys.argv) != 2:
    print >>sys.stderr, "Usage: win.py path/to/WinUser.h"
    sys.exit(1)
OUT = 'win2.txt'
TMP = OUT + '.tmp'
f = open(TMP, 'w')
try:
    print >>f, '; Automatically generated by "win.py"'
    VK = re.compile('#define\s*VK_(\w+)\s+(\w+)')
    for line in open(sys.argv[1], 'r'):
        m = VK.match(line)
        if m:
            n, i = m.groups()
            i = int(i, 0)
            print >>f, '%d\t%s' % (i, n)
    f.close()
    os.rename(TMP, OUT)
except:
    try:
        os.unlink(TMP)
    except OSError:
        pass
    raise

Add keycode table generator for Windows

Add keycode table generator for Windows

Response:
<INSERT> #!/usr/bin/env python
import re, sys, os
if len(sys.argv) != 2:
 <INSERT_END> <INSERT>   print >>sys.stderr, "Usage: win.py path/to/WinUser.h"
    sys.exit(1)
OUT = 'win2.txt'
TMP = OUT + '.tmp'
f = open(TMP, 'w')
try:
    print >>f, '; Automatically generated by "win.py"'
    VK = re.compile('#define\s*VK_(\w+)\s+(\w+)')
    for line in open(sys.argv[1], 'r'):
        m = VK.match(line)
        if m:
            n, i = m.groups()
            i = int(i, 0)
            print >>f, '%d\t%s' % (i, n)
    f.close()
    os.rename(TMP, OUT)
except:
    try:
        os.unlink(TMP)
    except OSError:
        pass
    raise
 <INSERT_END> <|endoftext|> #!/usr/bin/env python
import re, sys, os
if len(sys.argv) != 2:
    print >>sys.stderr, "Usage: win.py path/to/WinUser.h"
    sys.exit(1)
OUT = 'win2.txt'
TMP = OUT + '.tmp'
f = open(TMP, 'w')
try:
    print >>f, '; Automatically generated by "win.py"'
    VK = re.compile('#define\s*VK_(\w+)\s+(\w+)')
    for line in open(sys.argv[1], 'r'):
        m = VK.match(line)
        if m:
            n, i = m.groups()
            i = int(i, 0)
            print >>f, '%d\t%s' % (i, n)
    f.close()
    os.rename(TMP, OUT)
except:
    try:
        os.unlink(TMP)
    except OSError:
        pass
    raise

Prompt: Add keycode table generator for Windows


#!/usr/bin/env python3

import ftplib
import gzip
import os
import sys

host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3

ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
    (year, filename) = line.strip().split()
    for i in range(retries):
        sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year,
            filename, i + 1, retries))
        try:
            ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), open(filename, 'wb').write)
        except ftplib.all_errors as error:
            sys.stderr.write('%s\n' % error)
            continue
        count = 0
        for record in gzip.open(filename, 'rb'):
            print('%s\t%s' % (year, record.decode('ISO-8859-1').strip()))
            count += 1
        sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count))
        os.remove(filename)
        break
    else:
        ftp.quit()
        sys.exit(1)
ftp.quit()

Response:
<INSERT> os
import <INSERT_END> <REPLACE_OLD> (year, <REPLACE_NEW> (year,
            <REPLACE_END> <DELETE> data = bytearray()
        <DELETE_END> <REPLACE_OLD> data.extend)
 <REPLACE_NEW> open(filename, 'wb').write)
 <REPLACE_END> <REPLACE_OLD> records = gzip.decompress(data).decode('ISO-8859-1').split('\n')[0:-1]
 <REPLACE_NEW> count = 0
 <REPLACE_END> <REPLACE_OLD> records:
 <REPLACE_NEW> gzip.open(filename, 'rb'):
 <REPLACE_END> <REPLACE_OLD> record))
 <REPLACE_NEW> record.decode('ISO-8859-1').strip()))
            count += 1
 <REPLACE_END> <REPLACE_OLD> len(records)))
 <REPLACE_NEW> count))
        os.remove(filename)
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python3

import ftplib
import gzip
import os
import sys

host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3

ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
    (year, filename) = line.strip().split()
    for i in range(retries):
        sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year,
            filename, i + 1, retries))
        try:
            ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), open(filename, 'wb').write)
        except ftplib.all_errors as error:
            sys.stderr.write('%s\n' % error)
            continue
        count = 0
        for record in gzip.open(filename, 'rb'):
            print('%s\t%s' % (year, record.decode('ISO-8859-1').strip()))
            count += 1
        sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, count))
        os.remove(filename)
        break
    else:
        ftp.quit()
        sys.exit(1)
ftp.quit()

Prompt:
Decompress downloaded files from disk, not in memory

#!/usr/bin/env python3

import ftplib
import gzip
import sys

host = 'ftp.ncdc.noaa.gov'
base = '/pub/data/noaa'
retries = 3

ftp = ftplib.FTP(host)
ftp.login()
for line in sys.stdin:
    (year, filename) = line.strip().split()
    for i in range(retries):
        sys.stderr.write('reporter:status:Processing file %s/%s (FTP attempt %d of %d)\n' % (year, filename, i + 1, retries))
        data = bytearray()
        try:
            ftp.retrbinary('RETR %s/%s/%s' % (base, year, filename), data.extend)
        except ftplib.all_errors as error:
            sys.stderr.write('%s\n' % error)
            continue
        records = gzip.decompress(data).decode('ISO-8859-1').split('\n')[0:-1]
        for record in records:
            print('%s\t%s' % (year, record))
        sys.stderr.write('reporter:counter:NCDC Download,%s,%d\n' % (year, len(records)))
        break
    else:
        ftp.quit()
        sys.exit(1)
ftp.quit()


# Configuration file for ipython-notebook.

c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.open_browser = False
c.NotebookApp.port = 8888

# Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-
# For headerssent by the upstream reverse proxy. Necessary if the proxy handles
# SSL
c.NotebookApp.trust_xheaders = True

# Supply overrides for the tornado.web.Application that the IPython notebook
# uses.
c.NotebookApp.webapp_settings = {
    'X-Frame-Options': 'ALLOW FROM nature.com',
    'Content-Security-Policy': "frame-ancestors 'self' *.nature.com",
    'template_path':['/srv/ga/', '/srv/ipython/IPython/html',
                     '/srv/ipython/IPython/html/templates']
}

Set the content security policy

Set the content security policy

Response:
<INSERT> 'Content-Security-Policy': "frame-ancestors 'self' *.nature.com",
    <INSERT_END> <|endoftext|> # Configuration file for ipython-notebook.

c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.open_browser = False
c.NotebookApp.port = 8888

# Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-
# For headerssent by the upstream reverse proxy. Necessary if the proxy handles
# SSL
c.NotebookApp.trust_xheaders = True

# Supply overrides for the tornado.web.Application that the IPython notebook
# uses.
c.NotebookApp.webapp_settings = {
    'X-Frame-Options': 'ALLOW FROM nature.com',
    'Content-Security-Policy': "frame-ancestors 'self' *.nature.com",
    'template_path':['/srv/ga/', '/srv/ipython/IPython/html',
                     '/srv/ipython/IPython/html/templates']
}

Prompt:
Set the content security policy

# Configuration file for ipython-notebook.

c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.open_browser = False
c.NotebookApp.port = 8888

# Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-
# For headerssent by the upstream reverse proxy. Necessary if the proxy handles
# SSL
c.NotebookApp.trust_xheaders = True

# Supply overrides for the tornado.web.Application that the IPython notebook
# uses.
c.NotebookApp.webapp_settings = {
    'X-Frame-Options': 'ALLOW FROM nature.com',
    'template_path':['/srv/ga/', '/srv/ipython/IPython/html',
                     '/srv/ipython/IPython/html/templates']
}


from .dcct import DCCT
from .li_llrf import LiLLRF
from .rf import RF
from .sofb import SOFB
from .kicker import Kicker
from .septum import Septum
from .screen import Screen
from .bpm import BPM
from .ict import ICT
from .ict import TranspEff
from .egun import Bias
from .egun import Filament
from .egun import HVPS
from .timing import Timing

Add timing in devices init

DEV.ENH: Add timing in devices init

Response:
<REPLACE_OLD> HVPS
 <REPLACE_NEW> HVPS
from .timing import Timing
 <REPLACE_END> <|endoftext|> from .dcct import DCCT
from .li_llrf import LiLLRF
from .rf import RF
from .sofb import SOFB
from .kicker import Kicker
from .septum import Septum
from .screen import Screen
from .bpm import BPM
from .ict import ICT
from .ict import TranspEff
from .egun import Bias
from .egun import Filament
from .egun import HVPS
from .timing import Timing

Prompt:
DEV.ENH: Add timing in devices init

from .dcct import DCCT
from .li_llrf import LiLLRF
from .rf import RF
from .sofb import SOFB
from .kicker import Kicker
from .septum import Septum
from .screen import Screen
from .bpm import BPM
from .ict import ICT
from .ict import TranspEff
from .egun import Bias
from .egun import Filament
from .egun import HVPS


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

from django.db import migrations, models
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        ('flows', '0045_populate_responded'),
    ]

    operations = [
        migrations.AlterField(
            model_name='flowrun',
            name='responded',
            field=models.BooleanField(default=False, help_text='Whether contact has responded in this run'),
        ),
    ]

Set FlowRun.respnoded to be non-nullable

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

from django.db import migrations, models
from django.conf import settings

class Migration(migrations.Migration):

 <INSERT_END> <INSERT>   dependencies = [
        ('flows', '0045_populate_responded'),
    ]

    operations = [
        migrations.AlterField(
            model_name='flowrun',
            name='responded',
            field=models.BooleanField(default=False, help_text='Whether contact has responded in this run'),
        ),
    ]
 <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        ('flows', '0045_populate_responded'),
    ]

    operations = [
        migrations.AlterField(
            model_name='flowrun',
            name='responded',
            field=models.BooleanField(default=False, help_text='Whether contact has responded in this run'),
        ),
    ]

Prompt: Set FlowRun.respnoded to be non-nullable


from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.views.generic.base import RedirectView

urlpatterns = patterns('',
    url(r'^$', RedirectView.as_view(pattern_name='ticket_list', permanent=False)),
    (r'^ticket/', include('ticketus.ui.urls')),
    (r'^grappelli/', include('grappelli.urls')),
    (r'^admin/', include(admin.site.urls)),
)

if settings.DEBUG:
    import debug_toolbar
    urlpatterns += patterns('',
        (r'^__debug__/', include(debug_toolbar.urls)),
    )

    # Serve media files in development. Note Django automatically serves
    # static files as the staticfiles app is active in settings.py.
    from django.conf.urls.static import static
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Add CBV for redirecting / to /ticket

Add CBV for redirecting / to /ticket

Response:
<REPLACE_OLD> include
from <REPLACE_NEW> include, url
from <REPLACE_END> <REPLACE_OLD> admin

urlpatterns <REPLACE_NEW> admin
from django.views.generic.base import RedirectView

urlpatterns <REPLACE_END> <INSERT>    url(r'^$', RedirectView.as_view(pattern_name='ticket_list', permanent=False)),
 <INSERT_END> <|endoftext|> from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.views.generic.base import RedirectView

urlpatterns = patterns('',
    url(r'^$', RedirectView.as_view(pattern_name='ticket_list', permanent=False)),
    (r'^ticket/', include('ticketus.ui.urls')),
    (r'^grappelli/', include('grappelli.urls')),
    (r'^admin/', include(admin.site.urls)),
)

if settings.DEBUG:
    import debug_toolbar
    urlpatterns += patterns('',
        (r'^__debug__/', include(debug_toolbar.urls)),
    )

    # Serve media files in development. Note Django automatically serves
    # static files as the staticfiles app is active in settings.py.
    from django.conf.urls.static import static
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Prompt:
Add CBV for redirecting / to /ticket

from django.conf import settings
from django.conf.urls import patterns, include
from django.contrib import admin

urlpatterns = patterns('',
    (r'^ticket/', include('ticketus.ui.urls')),
    (r'^grappelli/', include('grappelli.urls')),
    (r'^admin/', include(admin.site.urls)),
)

if settings.DEBUG:
    import debug_toolbar
    urlpatterns += patterns('',
        (r'^__debug__/', include(debug_toolbar.urls)),
    )

    # Serve media files in development. Note Django automatically serves
    # static files as the staticfiles app is active in settings.py.
    from django.conf.urls.static import static
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


from hypothesis_auto import auto_pytest_magic

from isort import parse
from isort.settings import Config

TEST_CONTENTS = """
import xyz
import abc

def function():
    pass
"""

def test_file_contents():
    (
        in_lines,
        out_lines,
        import_index,
        place_imports,
        import_placements,
        as_map,
        imports,
        categorized_comments,
        first_comment_index_start,
        first_comment_index_end,
        change_count,
        original_line_count,
        line_separator,
        sections,
        section_comments,
    ) = parse.file_contents(TEST_CONTENTS, config=Config())
    assert "\n".join(in_lines) == TEST_CONTENTS
    assert "import" not in "\n".join(out_lines)
    assert import_index == 1
    assert change_count == -2
    assert original_line_count == len(in_lines)

auto_pytest_magic(parse.import_type)
auto_pytest_magic(parse.skip_line)
auto_pytest_magic(parse._strip_syntax)
auto_pytest_magic(parse._infer_line_separator)

Response:
<REPLACE_OLD> default

TEST_CONTENTS <REPLACE_NEW> Config

TEST_CONTENTS <REPLACE_END> <REPLACE_OLD> config=default)
 <REPLACE_NEW> config=Config())
 <REPLACE_END> <|endoftext|> from hypothesis_auto import auto_pytest_magic

from isort import parse
from isort.settings import Config

TEST_CONTENTS = """
import xyz
import abc

def function():
    pass
"""

def test_file_contents():
    (
        in_lines,
        out_lines,
        import_index,
        place_imports,
        import_placements,
        as_map,
        imports,
        categorized_comments,
        first_comment_index_start,
        first_comment_index_end,
        change_count,
        original_line_count,
        line_separator,
        sections,
        section_comments,
    ) = parse.file_contents(TEST_CONTENTS, config=Config())
    assert "\n".join(in_lines) == TEST_CONTENTS
    assert "import" not in "\n".join(out_lines)
    assert import_index == 1
    assert change_count == -2
    assert original_line_count == len(in_lines)

auto_pytest_magic(parse.import_type)
auto_pytest_magic(parse.skip_line)
auto_pytest_magic(parse._strip_syntax)
auto_pytest_magic(parse._infer_line_separator)

Prompt:
Fix use of default config to match new refactor

from hypothesis_auto import auto_pytest_magic

from isort import parse
from isort.settings import default

TEST_CONTENTS = """
import xyz
import abc

def function():
    pass
"""

def test_file_contents():
    (
        in_lines,
        out_lines,
        import_index,
        place_imports,
        import_placements,
        as_map,
        imports,
        categorized_comments,
        first_comment_index_start,
        first_comment_index_end,
        change_count,
        original_line_count,
        line_separator,
        sections,
        section_comments,
    ) = parse.file_contents(TEST_CONTENTS, config=default)
    assert "\n".join(in_lines) == TEST_CONTENTS
    assert "import" not in "\n".join(out_lines)
    assert import_index == 1
    assert change_count == -2
    assert original_line_count == len(in_lines)

auto_pytest_magic(parse.import_type)
auto_pytest_magic(parse.skip_line)
auto_pytest_magic(parse._strip_syntax)
auto_pytest_magic(parse._infer_line_separator)


"""Prints the current view hierarchy.

Usage: pv
"""
def print_view_hierarchy(debugger, command, result, internal_dict):
  debugger.GetCommandInterpreter().HandleCommand('po [[UIWindow keyWindow] recursiveDescription]', result)

def __lldb_init_module(debugger, internal_dict):
  debugger.HandleCommand('command script add -f print_view_hierarchy.print_view_hierarchy pv')

Response:
<REPLACE_OLD> debugger.HandleCommand('po <REPLACE_NEW> debugger.GetCommandInterpreter().HandleCommand('po <REPLACE_END> <REPLACE_OLD> recursiveDescription]')

def <REPLACE_NEW> recursiveDescription]', result)

def <REPLACE_END> <|endoftext|> """Prints the current view hierarchy.

Usage: pv
"""
def print_view_hierarchy(debugger, command, result, internal_dict):
  debugger.GetCommandInterpreter().HandleCommand('po [[UIWindow keyWindow] recursiveDescription]', result)

def __lldb_init_module(debugger, internal_dict):
  debugger.HandleCommand('command script add -f print_view_hierarchy.print_view_hierarchy pv')

Prompt:
Update view hierarchy script to use the interpreter as needed for tests.

"""Prints the current view hierarchy.

Usage: pv
"""
def print_view_hierarchy(debugger, command, result, internal_dict):
  debugger.HandleCommand('po [[UIWindow keyWindow] recursiveDescription]')

def __lldb_init_module(debugger, internal_dict):
  debugger.HandleCommand('command script add -f print_view_hierarchy.print_view_hierarchy pv')


import json
import logging
import requests
from requests.exceptions import RequestException, ConnectionError, HTTPError
import sys
from grading_service import GradingService
from grading_service import GradingServiceError

from django.conf import settings
from django.http import HttpResponse, Http404

log = logging.getLogger(__name__)

class ControllerQueryService(GradingService):
    """
    Interface to staff grading backend.
    """
    def __init__(self, config):
        super(ControllerQuery, self).__init__(config)
        self.check_eta_url = self.url + '/get_submission_eta/'
        self.is_unique_url = self.url + '/is_name_unique/'
        self.combined_notifications_url = self.url + '/combined_notifications/'

    def check_if_name_is_unique(self, location, problem_id, course_id):
        params = {
            'course_id': course_id,
            'location' : location,
            'problem_id' : problem_id
        }
        response = self.get(self.is_unique_url, params)
        return response

    def check_for_eta(self, location):
        params = {
            'location' : location,
        }
        response = self.get(self.check_eta_url, params)
        return response

    def check_combined_notifications(self, course_id, student_id):
        params= {
            'student_id' : student_id,
            'course_id' : course_id,
        }
        response = self.get(self.combined_notifications_url,params)
        return response

Response:
<REPLACE_OLD> '/is_name_unique/'

 <REPLACE_NEW> '/is_name_unique/'
        self.combined_notifications_url = self.url + '/combined_notifications/'

 <REPLACE_END> <REPLACE_OLD> response
 <REPLACE_NEW> response

    def check_combined_notifications(self, course_id, student_id):
        params= {
            'student_id' : student_id,
            'course_id' : course_id,
        }
        response = self.get(self.combined_notifications_url,params)
        return response

 <REPLACE_END> <|endoftext|> import json
import logging
import requests
from requests.exceptions import RequestException, ConnectionError, HTTPError
import sys
from grading_service import GradingService
from grading_service import GradingServiceError

from django.conf import settings
from django.http import HttpResponse, Http404

log = logging.getLogger(__name__)

class ControllerQueryService(GradingService):
    """
    Interface to staff grading backend.
    """
    def __init__(self, config):
        super(ControllerQuery, self).__init__(config)
        self.check_eta_url = self.url + '/get_submission_eta/'
        self.is_unique_url = self.url + '/is_name_unique/'
        self.combined_notifications_url = self.url + '/combined_notifications/'

    def check_if_name_is_unique(self, location, problem_id, course_id):
        params = {
            'course_id': course_id,
            'location' : location,
            'problem_id' : problem_id
        }
        response = self.get(self.is_unique_url, params)
        return response

    def check_for_eta(self, location):
        params = {
            'location' : location,
        }
        response = self.get(self.check_eta_url, params)
        return response

    def check_combined_notifications(self, course_id, student_id):
        params= {
            'student_id' : student_id,
            'course_id' : course_id,
        }
        response = self.get(self.combined_notifications_url,params)
        return response

Prompt:
Add in an item to check for combined notifications

import json
import logging
import requests
from requests.exceptions import RequestException, ConnectionError, HTTPError
import sys
from grading_service import GradingService
from grading_service import GradingServiceError

from django.conf import settings
from django.http import HttpResponse, Http404

log = logging.getLogger(__name__)

class ControllerQueryService(GradingService):
    """
    Interface to staff grading backend.
    """
    def __init__(self, config):
        super(ControllerQuery, self).__init__(config)
        self.check_eta_url = self.url + '/get_submission_eta/'
        self.is_unique_url = self.url + '/is_name_unique/'

    def check_if_name_is_unique(self, location, problem_id, course_id):
        params = {
            'course_id': course_id,
            'location' : location,
            'problem_id' : problem_id
        }
        response = self.get(self.is_unique_url, params)
        return response

    def check_for_eta(self, location):
        params = {
            'location' : location,
        }
        response = self.get(self.check_eta_url, params)
        return response


import glob
import unittest
import os, sys

if __name__ == '__main__':
    PROJECT_ROOT = os.path.dirname(__file__)
    test_file_strings = glob.glob(os.path.join(PROJECT_ROOT, 'test_*.py'))
    module_strings = [os.path.splitext(os.path.basename(str))[0] for str in test_file_strings]
    suites = [unittest.defaultTestLoader.loadTestsFromName(str) for str in module_strings]
    testSuite = unittest.TestSuite(suites)
    text_runner = unittest.TextTestRunner().run(testSuite)

Add all test runner for command line. Now every test can be run for commandline

Response:
<INSERT> import glob
import unittest
import os, sys

if __name__ == '__main__':
 <INSERT_END> <INSERT>   PROJECT_ROOT = os.path.dirname(__file__)
    test_file_strings = glob.glob(os.path.join(PROJECT_ROOT, 'test_*.py'))
    module_strings = [os.path.splitext(os.path.basename(str))[0] for str in test_file_strings]
    suites = [unittest.defaultTestLoader.loadTestsFromName(str) for str in module_strings]
    testSuite = unittest.TestSuite(suites)
    text_runner = unittest.TextTestRunner().run(testSuite)
 <INSERT_END> <|endoftext|> import glob
import unittest
import os, sys

if __name__ == '__main__':
    PROJECT_ROOT = os.path.dirname(__file__)
    test_file_strings = glob.glob(os.path.join(PROJECT_ROOT, 'test_*.py'))
    module_strings = [os.path.splitext(os.path.basename(str))[0] for str in test_file_strings]
    suites = [unittest.defaultTestLoader.loadTestsFromName(str) for str in module_strings]
    testSuite = unittest.TestSuite(suites)
    text_runner = unittest.TextTestRunner().run(testSuite)

Prompt: Add all test runner for command line. Now every test can be run for commandline


# -*- coding: utf-8 -*-
"""Asynchronous task queue module."""

from celery import Celery
from celery.utils.log import get_task_logger

from raven import Client
from raven.contrib.celery import register_signal

from website import settings

app = Celery()

# TODO: Hardcoded settings module. Should be set using framework's config handler
app.config_from_object('website.settings')

if settings.SENTRY_DSN:
    client = Client(settings.SENTRY_DSN)
    register_signal(client)

@app.task
def error_handler(task_id, task_name):
    """logs detailed message about tasks that raise exceptions

    :param task_id: TaskID of the failed task
    :param task_name: name of task that failed
    """
    # get the current logger
    logger = get_task_logger(__name__)
    # query the broker for the AsyncResult
    result = app.AsyncResult(task_id)
    excep = result.get(propagate=False)
    # log detailed error mesage in error log
    logger.error('#####FAILURE LOG BEGIN#####\n'
                'Task {0} raised exception: {0}\n\{0}\n'
                '#####FAILURE LOG STOP#####'.format(task_name, excep, result.traceback))

Use auto generated celery queues

Use auto generated celery queues

Response:
<REPLACE_OLD> get_task_logger
from kombu import Exchange, Queue

from <REPLACE_NEW> get_task_logger

from <REPLACE_END> <REPLACE_OLD> handler
app.config_from_object('website.settings')

app.conf.CELERY_QUEUES = (
    Queue(
        settings.CELERY_DEFAULT_QUEUE,
        Exchange(settings.CELERY_DEFAULT_QUEUE),
        routing_key=settings.CELERY_DEFAULT_QUEUE),
)

if <REPLACE_NEW> handler
app.config_from_object('website.settings')

if <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
"""Asynchronous task queue module."""

from celery import Celery
from celery.utils.log import get_task_logger

from raven import Client
from raven.contrib.celery import register_signal

from website import settings

app = Celery()

# TODO: Hardcoded settings module. Should be set using framework's config handler
app.config_from_object('website.settings')

if settings.SENTRY_DSN:
    client = Client(settings.SENTRY_DSN)
    register_signal(client)

@app.task
def error_handler(task_id, task_name):
    """logs detailed message about tasks that raise exceptions

    :param task_id: TaskID of the failed task
    :param task_name: name of task that failed
    """
    # get the current logger
    logger = get_task_logger(__name__)
    # query the broker for the AsyncResult
    result = app.AsyncResult(task_id)
    excep = result.get(propagate=False)
    # log detailed error mesage in error log
    logger.error('#####FAILURE LOG BEGIN#####\n'
                'Task {0} raised exception: {0}\n\{0}\n'
                '#####FAILURE LOG STOP#####'.format(task_name, excep, result.traceback))

Prompt:
Use auto generated celery queues

# -*- coding: utf-8 -*-
"""Asynchronous task queue module."""

from celery import Celery
from celery.utils.log import get_task_logger
from kombu import Exchange, Queue

from raven import Client
from raven.contrib.celery import register_signal

from website import settings

app = Celery()

# TODO: Hardcoded settings module. Should be set using framework's config handler
app.config_from_object('website.settings')

app.conf.CELERY_QUEUES = (
    Queue(
        settings.CELERY_DEFAULT_QUEUE,
        Exchange(settings.CELERY_DEFAULT_QUEUE),
        routing_key=settings.CELERY_DEFAULT_QUEUE),
)

if settings.SENTRY_DSN:
    client = Client(settings.SENTRY_DSN)
    register_signal(client)

@app.task
def error_handler(task_id, task_name):
    """logs detailed message about tasks that raise exceptions

    :param task_id: TaskID of the failed task
    :param task_name: name of task that failed
    """
    # get the current logger
    logger = get_task_logger(__name__)
    # query the broker for the AsyncResult
    result = app.AsyncResult(task_id)
    excep = result.get(propagate=False)
    # log detailed error mesage in error log
    logger.error('#####FAILURE LOG BEGIN#####\n'
                'Task {0} raised exception: {0}\n\{0}\n'
                '#####FAILURE LOG STOP#####'.format(task_name, excep, result.traceback))


# -*- coding: UTF-8 -*-
"""
Recipe for loading additional step definitions from sub-directories
in the "features/steps" directory.

.. code-block::

    # -- FILE: features/steps/use_substep_dirs.py
    # REQUIRES: path.py
    from behave.runner_util import load_step_modules
    from path import Path

    HERE = Path(__file__).dirname()
    SUBSTEP_DIRS = list(HERE.walkdirs())
    load_step_modules(SUBSTEP_DIRS)
"""

FIX TYPO: Uncovered by NaveenKVN

FIX TYPO: Uncovered by NaveenKVN

Response:
<REPLACE_OLD> load_step_modules
 <REPLACE_NEW> load_step_modules
 <REPLACE_END> <REPLACE_OLD> Path

 <REPLACE_NEW> Path

 <REPLACE_END> <REPLACE_OLD> Path(__file__).dirname
 <REPLACE_NEW> Path(__file__).dirname()
 <REPLACE_END> <|endoftext|> # -*- coding: UTF-8 -*-
"""
Recipe for loading additional step definitions from sub-directories
in the "features/steps" directory.

.. code-block::

    # -- FILE: features/steps/use_substep_dirs.py
    # REQUIRES: path.py
    from behave.runner_util import load_step_modules
    from path import Path

    HERE = Path(__file__).dirname()
    SUBSTEP_DIRS = list(HERE.walkdirs())
    load_step_modules(SUBSTEP_DIRS)
"""

Prompt:
FIX TYPO: Uncovered by NaveenKVN

# -*- coding: UTF-8 -*-
"""
Recipe for loading additional step definitions from sub-directories
in the "features/steps" directory.

.. code-block::

    # -- FILE: features/steps/use_substep_dirs.py
    # REQUIRES: path.py
    from behave.runner_util import load_step_modules
    from path import Path

    HERE = Path(__file__).dirname
    SUBSTEP_DIRS = list(HERE.walkdirs())
    load_step_modules(SUBSTEP_DIRS)
"""


#!/usr/bin/env python

import argparse
import os
import yaml
from genologics.lims import Lims
from genologics.entities import Project
from genologics.config import BASEURI, USERNAME, PASSWORD
import LIMS2DB.utils as lutils
from requests.exceptions import HTTPError

def main(args):
    log = lutils.setupLog('bioinfologger', args.logfile)
    lims = Lims(BASEURI, USERNAME, PASSWORD)
    with open(args.conf) as conf_file:
        conf = yaml.safe_load(conf_file)
    bioinfodb = lutils.setupServer(conf)['bioinfo_analysis']
    open_projects = bioinfodb.view('latest_data/sample_id_open')

    for row in open_projects.rows:
        project_id = row.key[0]
        sample_id = row.key[3]
        close_date = None
        try:
            close_date = Project(lims=lims, id=project_id).close_date
        except HTTPError as e:
            if '404: Project not found' in e.message:
                log.error('Project '+project_id+' not found in LIMS')
                continue
        if close_date is not None:
            try:
                doc = bioinfodb.get(row.id)
            except Exception as e:
                log.error(e + 'in Project '+project_id+ ' Sample '+sample_id+ ' while accessing doc from statusdb')
            doc['project_closed'] = True
            try:
                bioinfodb.save(doc)
                log.info('Updated Project '+project_id+ ' Sample '+sample_id)
            except Exception as e:
                log.error(e + 'in Project '+project_id+ ' Sample '+sample_id+ ' while saving to statusdb')

if __name__ == '__main__':
    usage = "Usage:       python bioinfo_project_status_update.py [options]"
    parser = argparse.ArgumentParser(description=usage)

    parser.add_argument("-c", "--conf", dest="conf",
    default=os.path.join(os.environ['HOME'],'opt/config/post_process.yaml'),
    help = "Config file.  Default: ~/opt/config/post_process.yaml")

    parser.add_argument("-l", "--log", dest="logfile",
    default=os.path.join(os.environ['HOME'],'statusdb_bioinfo_closed.log'),
    help = "log file.  Default: ~/statusdb_bioinfo_closed.log")
    args = parser.parse_args()

    main(args)

Add script to update project closure in bioinfo_analysis db

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

import argparse
import os
import yaml
from genologics.lims import Lims
from genologics.entities import Project
from genologics.config import BASEURI, USERNAME, PASSWORD
import LIMS2DB.utils as lutils
from requests.exceptions import HTTPError

def main(args):
    log = lutils.setupLog('bioinfologger', args.logfile)
    lims = Lims(BASEURI, USERNAME, PASSWORD)
    with open(args.conf) as conf_file:
        conf = yaml.safe_load(conf_file)
    bioinfodb = lutils.setupServer(conf)['bioinfo_analysis']
    open_projects = bioinfodb.view('latest_data/sample_id_open')

    for row in open_projects.rows:
        project_id = row.key[0]
        sample_id = row.key[3]
        close_date = None
        try:
            close_date = Project(lims=lims, id=project_id).close_date
        except HTTPError as e:
            if '404: Project not found' in e.message:
                log.error('Project '+project_id+' not found in LIMS')
                continue
        if close_date is not None:
            try:
                doc = bioinfodb.get(row.id)
            except Exception as e:
                log.error(e + 'in Project '+project_id+ ' Sample '+sample_id+ ' while accessing doc from statusdb')
            doc['project_closed'] = True
            try:
                bioinfodb.save(doc)
                log.info('Updated Project '+project_id+ ' Sample '+sample_id)
            except Exception as e:
                log.error(e + 'in Project '+project_id+ ' Sample '+sample_id+ ' while saving to statusdb')

if __name__ == '__main__':
    usage = "Usage:       python bioinfo_project_status_update.py [options]"
    parser = argparse.ArgumentParser(description=usage)

    parser.add_argument("-c", "--conf", dest="conf",
    default=os.path.join(os.environ['HOME'],'opt/config/post_process.yaml'),
    help = "Config file.  Default: ~/opt/config/post_process.yaml")

    parser.add_argument("-l", "--log", dest="logfile",
    default=os.path.join(os.environ['HOME'],'statusdb_bioinfo_closed.log'),
    help = "log file.  Default: ~/statusdb_bioinfo_closed.log")
    args = parser.parse_args()

    main(args)
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

import argparse
import os
import yaml
from genologics.lims import Lims
from genologics.entities import Project
from genologics.config import BASEURI, USERNAME, PASSWORD
import LIMS2DB.utils as lutils
from requests.exceptions import HTTPError

def main(args):
    log = lutils.setupLog('bioinfologger', args.logfile)
    lims = Lims(BASEURI, USERNAME, PASSWORD)
    with open(args.conf) as conf_file:
        conf = yaml.safe_load(conf_file)
    bioinfodb = lutils.setupServer(conf)['bioinfo_analysis']
    open_projects = bioinfodb.view('latest_data/sample_id_open')

    for row in open_projects.rows:
        project_id = row.key[0]
        sample_id = row.key[3]
        close_date = None
        try:
            close_date = Project(lims=lims, id=project_id).close_date
        except HTTPError as e:
            if '404: Project not found' in e.message:
                log.error('Project '+project_id+' not found in LIMS')
                continue
        if close_date is not None:
            try:
                doc = bioinfodb.get(row.id)
            except Exception as e:
                log.error(e + 'in Project '+project_id+ ' Sample '+sample_id+ ' while accessing doc from statusdb')
            doc['project_closed'] = True
            try:
                bioinfodb.save(doc)
                log.info('Updated Project '+project_id+ ' Sample '+sample_id)
            except Exception as e:
                log.error(e + 'in Project '+project_id+ ' Sample '+sample_id+ ' while saving to statusdb')

if __name__ == '__main__':
    usage = "Usage:       python bioinfo_project_status_update.py [options]"
    parser = argparse.ArgumentParser(description=usage)

    parser.add_argument("-c", "--conf", dest="conf",
    default=os.path.join(os.environ['HOME'],'opt/config/post_process.yaml'),
    help = "Config file.  Default: ~/opt/config/post_process.yaml")

    parser.add_argument("-l", "--log", dest="logfile",
    default=os.path.join(os.environ['HOME'],'statusdb_bioinfo_closed.log'),
    help = "log file.  Default: ~/statusdb_bioinfo_closed.log")
    args = parser.parse_args()

    main(args)

Prompt: Add script to update project closure in bioinfo_analysis db


from setuptools import setup, find_packages

package_data = ['static/css/*', 'static/img/*', 'static/js/*', 'static/js/templates/*', 'templates/djukebox/*']
dependencies = ['Pillow==2.1.0', 'django-celery==3.0.21', 'mutagen==1.21', 'simplejson==3.3.0', 'django-bootstrap-form', 'django-tastypie==0.9.15']
setup(name = "djukebox",
      version = "0.2.0",
      description = "A django HTML 5 audio player",
      author = "Justin Michalicek",
      author_email = "jmichalicek@gmail.com",
      url = "https://github.com/jmichalicek/djukebox/",
      license = "www.opensource.org/licenses/bsd-license.php",
      packages = find_packages(),
      #'package' package must contain files (see list above)
      package_data = {'djukebox' : package_data },
      install_requires = dependencies,
      long_description = """A HTML 5 audio player using Django"""
      #This next part it for the Cheese Shop, look a little down the page.
      #classifiers = []
)

Response:
<REPLACE_OLD> ['pillow', 'django-celery==2.5.5', 'mutagen', 'simplejson', <REPLACE_NEW> ['Pillow==2.1.0', 'django-celery==3.0.21', 'mutagen==1.21', 'simplejson==3.3.0', <REPLACE_END> <|endoftext|> from setuptools import setup, find_packages

package_data = ['static/css/*', 'static/img/*', 'static/js/*', 'static/js/templates/*', 'templates/djukebox/*']
dependencies = ['Pillow==2.1.0', 'django-celery==3.0.21', 'mutagen==1.21', 'simplejson==3.3.0', 'django-bootstrap-form', 'django-tastypie==0.9.15']
setup(name = "djukebox",
      version = "0.2.0",
      description = "A django HTML 5 audio player",
      author = "Justin Michalicek",
      author_email = "jmichalicek@gmail.com",
      url = "https://github.com/jmichalicek/djukebox/",
      license = "www.opensource.org/licenses/bsd-license.php",
      packages = find_packages(),
      #'package' package must contain files (see list above)
      package_data = {'djukebox' : package_data },
      install_requires = dependencies,
      long_description = """A HTML 5 audio player using Django"""
      #This next part it for the Cheese Shop, look a little down the page.
      #classifiers = []
)

Prompt:
Set full versions on all dependencies and updated most to latest version

from setuptools import setup, find_packages

package_data = ['static/css/*', 'static/img/*', 'static/js/*', 'static/js/templates/*', 'templates/djukebox/*']
dependencies = ['pillow', 'django-celery==2.5.5', 'mutagen', 'simplejson', 'django-bootstrap-form', 'django-tastypie==0.9.15']
setup(name = "djukebox",
      version = "0.2.0",
      description = "A django HTML 5 audio player",
      author = "Justin Michalicek",
      author_email = "jmichalicek@gmail.com",
      url = "https://github.com/jmichalicek/djukebox/",
      license = "www.opensource.org/licenses/bsd-license.php",
      packages = find_packages(),
      #'package' package must contain files (see list above)
      package_data = {'djukebox' : package_data },
      install_requires = dependencies,
      long_description = """A HTML 5 audio player using Django"""
      #This next part it for the Cheese Shop, look a little down the page.
      #classifiers = []
)


from django.test import TestCase
from chatterbot.ext.django_chatterbot.models import Statement

class OutputIntegrationTestCase(TestCase):
    """
    Tests to make sure that output adapters
    function correctly when using Django.
    """

    def test_output_format_adapter(self):
        from chatterbot.output import OutputFormatAdapter

        adapter = OutputFormatAdapter()

        statement = Statement(text='_')
        result = adapter.process_response(statement)

        self.assertEqual(result.text, '_')

Test that the output format adapter works with Django

Response:
<INSERT> from django.test import TestCase
from chatterbot.ext.django_chatterbot.models import Statement

class OutputIntegrationTestCase(TestCase):
 <INSERT_END> <INSERT>   """
    Tests to make sure that output adapters
    function correctly when using Django.
    """

    def test_output_format_adapter(self):
        from chatterbot.output import OutputFormatAdapter

        adapter = OutputFormatAdapter()

        statement = Statement(text='_')
        result = adapter.process_response(statement)

        self.assertEqual(result.text, '_')
 <INSERT_END> <|endoftext|> from django.test import TestCase
from chatterbot.ext.django_chatterbot.models import Statement

class OutputIntegrationTestCase(TestCase):
    """
    Tests to make sure that output adapters
    function correctly when using Django.
    """

    def test_output_format_adapter(self):
        from chatterbot.output import OutputFormatAdapter

        adapter = OutputFormatAdapter()

        statement = Statement(text='_')
        result = adapter.process_response(statement)

        self.assertEqual(result.text, '_')

Prompt: Test that the output format adapter works with Django


#!/usr/bin/python

import sys

def fib(n):
 a,b = 0,1
 yield a
 if n>0 :
  yield b
  for i in range(2,n+1):
   a,b = b, a+b
   yield b

num = int(sys.argv[1])
gen = fib(num)
for i in gen:
 print i

Add function for Fibonacci sequence

Add function for Fibonacci sequence

Response:
<INSERT> #!/usr/bin/python

import sys

def fib(n):
 a,b = 0,1
 yield a
 if n>0 :
 <INSERT_END> <INSERT> yield b
  for i in range(2,n+1):
   a,b = b, a+b
   yield b

num = int(sys.argv[1])
gen = fib(num)
for i in gen:
 print i
 <INSERT_END> <|endoftext|> #!/usr/bin/python

import sys

def fib(n):
 a,b = 0,1
 yield a
 if n>0 :
  yield b
  for i in range(2,n+1):
   a,b = b, a+b
   yield b

num = int(sys.argv[1])
gen = fib(num)
for i in gen:
 print i

Prompt: Add function for Fibonacci sequence


from cyclone import web
from oonib.deck import handlers
from oonib import config

deckAPI = [
    (r"/deck", handlers.DeckListHandler),
    (r"/deck/([a-z0-9]{64})$", handlers.DeckDescHandler),
    (r"/deck/([a-z0-9]{64})/yaml$", web.StaticFileHandler, {"path":
        config.main.deck_dir}),
]

Use sha256 as per oonib.md spec

Use sha256 as per oonib.md spec

Response:
<REPLACE_OLD> (r"/deck/([a-z0-9]{40})$", <REPLACE_NEW> (r"/deck/([a-z0-9]{64})$", <REPLACE_END> <REPLACE_OLD> (r"/deck/([a-z0-9]{40})/yaml$", <REPLACE_NEW> (r"/deck/([a-z0-9]{64})/yaml$", <REPLACE_END> <|endoftext|> from cyclone import web
from oonib.deck import handlers
from oonib import config

deckAPI = [
    (r"/deck", handlers.DeckListHandler),
    (r"/deck/([a-z0-9]{64})$", handlers.DeckDescHandler),
    (r"/deck/([a-z0-9]{64})/yaml$", web.StaticFileHandler, {"path":
        config.main.deck_dir}),
]

Prompt:
Use sha256 as per oonib.md spec

from cyclone import web
from oonib.deck import handlers
from oonib import config

deckAPI = [
    (r"/deck", handlers.DeckListHandler),
    (r"/deck/([a-z0-9]{40})$", handlers.DeckDescHandler),
    (r"/deck/([a-z0-9]{40})/yaml$", web.StaticFileHandler, {"path":
        config.main.deck_dir}),
]


from tfidf_lsa import calculate_corpus_var
import json
import os
import shutil
import subprocess
import unittest

class TestMoviePepper(unittest.TestCase):

    def test_crawl(self):
        try:
            shutil.rmtree('./movie_scrape/crawls')
            os.remove('./movie_scrape/imdb.json')
            os.remove('./db.json')
        except FileNotFoundError:
            pass
        except OSError:
            pass

        subprocess.run(['START_URL="http://www.imdb.com/search/title?role=nm0000095&title_type=feature&user_rating=8.0,10" ./scrap.sh'], cwd="./movie_scrape/", shell=True)

        try:
            with open('./movie_scrape/imdb.json', 'r') as in_file:
                json.load(in_file)
        except:
            self.fail()

    def test_tfidf_lsa(self):
        calculate_corpus_var(max_df=200, min_df=2, n_components=10, max_features=None)

        try:
            with open('./db.json', 'r') as in_file:
                json.load(in_file)
        except:
            self.fail()

if __name__ == '__main__':
    unittest.main()

Add a basic crawler and tfidf_lsa creation test

Response:
<REPLACE_OLD>  <REPLACE_NEW> from tfidf_lsa import calculate_corpus_var
import json
import os
import shutil
import subprocess
import unittest

class TestMoviePepper(unittest.TestCase):

    def test_crawl(self):
        try:
            shutil.rmtree('./movie_scrape/crawls')
            os.remove('./movie_scrape/imdb.json')
            os.remove('./db.json')
        except FileNotFoundError:
            pass
        except OSError:
            pass

        subprocess.run(['START_URL="http://www.imdb.com/search/title?role=nm0000095&title_type=feature&user_rating=8.0,10" ./scrap.sh'], cwd="./movie_scrape/", shell=True)

        try:
            with open('./movie_scrape/imdb.json', 'r') as in_file:
                json.load(in_file)
        except:
            self.fail()

    def test_tfidf_lsa(self):
        calculate_corpus_var(max_df=200, min_df=2, n_components=10, max_features=None)

        try:
            with open('./db.json', 'r') as in_file:
                json.load(in_file)
        except:
            self.fail()

if __name__ == '__main__':
    unittest.main()
 <REPLACE_END> <|endoftext|> from tfidf_lsa import calculate_corpus_var
import json
import os
import shutil
import subprocess
import unittest

class TestMoviePepper(unittest.TestCase):

    def test_crawl(self):
        try:
            shutil.rmtree('./movie_scrape/crawls')
            os.remove('./movie_scrape/imdb.json')
            os.remove('./db.json')
        except FileNotFoundError:
            pass
        except OSError:
            pass

        subprocess.run(['START_URL="http://www.imdb.com/search/title?role=nm0000095&title_type=feature&user_rating=8.0,10" ./scrap.sh'], cwd="./movie_scrape/", shell=True)

        try:
            with open('./movie_scrape/imdb.json', 'r') as in_file:
                json.load(in_file)
        except:
            self.fail()

    def test_tfidf_lsa(self):
        calculate_corpus_var(max_df=200, min_df=2, n_components=10, max_features=None)

        try:
            with open('./db.json', 'r') as in_file:
                json.load(in_file)
        except:
            self.fail()

if __name__ == '__main__':
    unittest.main()

Prompt: Add a basic crawler and tfidf_lsa creation test


import csv

class Table():
    '''A Table is an object which represents a 2-dimensional CSV file. Both rows
    and columns can be accessed via their key as in a dictionary. This means that
    keys cannot appear as both a row and column label.'''

    def __init__(self, filename):
        self._internal_table = self.load_from_filename(filename)

    def load_from_filename(self, filename):
        '''Load a CSV file into a list of lists. The following CSV:
            ,a,b,c
           d,1,2,3
           e,4,5,6
           f,7,8,9
        would become the list:
           [['', 'a', 'b', 'c'],
            ['d', '1', '2', '3'] ...]'''
        with open(filename, 'r') as f:
            reader = csv.reader(f)
            return [row for row in reader]

    def get_row(self, key):
        '''Gets a list containing all elements of the row specified by key.
        Returns a ValueError if the row doesn't exist.'''
        for row in self._internal_table:
            if row[0] == key:
                return row[1:]
        raise ValueError('Row not found')

    def get_column(self, key):
        '''Gets a list containing all elements of the column specified by key.
        Returns a ValueError if the column doesn't exist.'''
        for i, column in enumerate(self._internal_table[0]):
            if column == key:
                return [row[i] for row in self._internal_table[1:]]
        raise ValueError('Column not found')

    def __getitem__(self, key):
        '''Returns the row or column linked to the given key, accessed using
        subscript notation.'''
        if not isinstance(key, str):
            raise TypeError('Key must be a string')

        try:
            return self.get_row(key)
        except ValueError:
            try:
                return self.get_column(key)
            except ValueError:
                raise ValueError('Key not found in table')

Create Table object for representing phonetic inventory

Response:
<REPLACE_OLD>  <REPLACE_NEW> import csv

class Table():
    '''A Table is an object which represents a 2-dimensional CSV file. Both rows
    and columns can be accessed via their key as in a dictionary. This means that
    keys cannot appear as both a row and column label.'''

    def __init__(self, filename):
        self._internal_table = self.load_from_filename(filename)

    def load_from_filename(self, filename):
        '''Load a CSV file into a list of lists. The following CSV:
            ,a,b,c
           d,1,2,3
           e,4,5,6
           f,7,8,9
        would become the list:
           [['', 'a', 'b', 'c'],
            ['d', '1', '2', '3'] ...]'''
        with open(filename, 'r') as f:
            reader = csv.reader(f)
            return [row for row in reader]

    def get_row(self, key):
        '''Gets a list containing all elements of the row specified by key.
        Returns a ValueError if the row doesn't exist.'''
        for row in self._internal_table:
            if row[0] == key:
                return row[1:]
        raise ValueError('Row not found')

    def get_column(self, key):
        '''Gets a list containing all elements of the column specified by key.
        Returns a ValueError if the column doesn't exist.'''
        for i, column in enumerate(self._internal_table[0]):
            if column == key:
                return [row[i] for row in self._internal_table[1:]]
        raise ValueError('Column not found')

    def __getitem__(self, key):
        '''Returns the row or column linked to the given key, accessed using
        subscript notation.'''
        if not isinstance(key, str):
            raise TypeError('Key must be a string')

        try:
            return self.get_row(key)
        except ValueError:
            try:
                return self.get_column(key)
            except ValueError:
                raise ValueError('Key not found in table')
 <REPLACE_END> <|endoftext|> import csv

class Table():
    '''A Table is an object which represents a 2-dimensional CSV file. Both rows
    and columns can be accessed via their key as in a dictionary. This means that
    keys cannot appear as both a row and column label.'''

    def __init__(self, filename):
        self._internal_table = self.load_from_filename(filename)

    def load_from_filename(self, filename):
        '''Load a CSV file into a list of lists. The following CSV:
            ,a,b,c
           d,1,2,3
           e,4,5,6
           f,7,8,9
        would become the list:
           [['', 'a', 'b', 'c'],
            ['d', '1', '2', '3'] ...]'''
        with open(filename, 'r') as f:
            reader = csv.reader(f)
            return [row for row in reader]

    def get_row(self, key):
        '''Gets a list containing all elements of the row specified by key.
        Returns a ValueError if the row doesn't exist.'''
        for row in self._internal_table:
            if row[0] == key:
                return row[1:]
        raise ValueError('Row not found')

    def get_column(self, key):
        '''Gets a list containing all elements of the column specified by key.
        Returns a ValueError if the column doesn't exist.'''
        for i, column in enumerate(self._internal_table[0]):
            if column == key:
                return [row[i] for row in self._internal_table[1:]]
        raise ValueError('Column not found')

    def __getitem__(self, key):
        '''Returns the row or column linked to the given key, accessed using
        subscript notation.'''
        if not isinstance(key, str):
            raise TypeError('Key must be a string')

        try:
            return self.get_row(key)
        except ValueError:
            try:
                return self.get_column(key)
            except ValueError:
                raise ValueError('Key not found in table')

Prompt: Create Table object for representing phonetic inventory


from praw.models import ModmailConversation

from ... import UnitTest

class TestModmailConversation(UnitTest):
    def test_parse(self):
        conversation = ModmailConversation(self.reddit,
                                           _data={'id': 'ik72'})
        assert str(conversation) == 'ik72'

Test that ModmailConversation.id is preserved after fetch

Response:
<INSERT> from praw.models import ModmailConversation

from ... import UnitTest

class TestModmailConversation(UnitTest):
 <INSERT_END> <INSERT>   def test_parse(self):
        conversation = ModmailConversation(self.reddit,
                                           _data={'id': 'ik72'})
        assert str(conversation) == 'ik72'
 <INSERT_END> <|endoftext|> from praw.models import ModmailConversation

from ... import UnitTest

class TestModmailConversation(UnitTest):
    def test_parse(self):
        conversation = ModmailConversation(self.reddit,
                                           _data={'id': 'ik72'})
        assert str(conversation) == 'ik72'

Prompt: Test that ModmailConversation.id is preserved after fetch


Response:
<REPLACE_OLD> from .ReinhardNorm import ReinhardNorm
from .ReinhardSample import ReinhardSample

__all__ <REPLACE_NEW> __all__ <REPLACE_END> <|endoftext|> __all__ = (
    'FeatureExtraction'
)

Prompt:
Resolve import issue in color_normalization_test

from .ReinhardNorm import ReinhardNorm
from .ReinhardSample import ReinhardSample

__all__ = (
    'FeatureExtraction'
)


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

import pbr.version

__version__ = pbr.version.VersionInfo('python-keystoneclient').version_string()

Fix --version to output version

Response:
<REPLACE_OLD> inspect
import os

def _get_client_version():
    """Read version from versioninfo file."""
    mod_abspath <REPLACE_NEW> pbr.version

__version__ <REPLACE_END> <REPLACE_OLD> inspect.getabsfile(inspect.currentframe())
    client_path = os.path.dirname(mod_abspath)
    version_path = os.path.join(client_path, 'versioninfo')

    if os.path.exists(version_path):
        version = open(version_path).read().strip()
    else:
        version = "Unknown, couldn't find versioninfo file at %s"\
                  % version_path

    return version

__version__ = _get_client_version()
 <REPLACE_NEW> pbr.version.VersionInfo('python-keystoneclient').version_string()
 <REPLACE_END> <|endoftext|> # Copyright 2012 OpenStack LLC.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import pbr.version

__version__ = pbr.version.VersionInfo('python-keystoneclient').version_string()

Prompt:
Fix --version to output version

Change-Id: I7d8dc83ac7c2ad7519633d136c1c32ce8537dce8
Fixes: bug 1182675

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

import inspect
import os

def _get_client_version():
    """Read version from versioninfo file."""
    mod_abspath = inspect.getabsfile(inspect.currentframe())
    client_path = os.path.dirname(mod_abspath)
    version_path = os.path.join(client_path, 'versioninfo')

    if os.path.exists(version_path):
        version = open(version_path).read().strip()
    else:
        version = "Unknown, couldn't find versioninfo file at %s"\
                  % version_path

    return version

__version__ = _get_client_version()


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

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html

import json,os
from datetime import datetime
from scrapy.exporters import JsonLinesItemExporter

path = "downloads"

class OnlineparticipationdatasetPipeline(object):
    def process_item(self, item, spider):
        return item

class JsonWriterPipeline(object):

    def open_spider(self, spider):
        if not os.path.isdir(path):
            os.makedirs(path)
        self.file = open("downloads/items_"+spider.name+".json", 'wb')
        self.exporter = JsonLinesItemExporter(self.file, encoding='utf-8', ensure_ascii=False)
        self.exporter.start_exporting()

    def close_spider(self, spider):
        self.exporter.finish_exporting()
        self.file.close()

    def process_item(self, item, spider):
        self.exporter.export_item(item)
        return item

Create path if it doesnt exists

Create path if it doesnt exists

Response:
<REPLACE_OLD> json
from <REPLACE_NEW> json,os
from <REPLACE_END> <REPLACE_OLD> JsonLinesItemExporter

class <REPLACE_NEW> JsonLinesItemExporter

path = "downloads"

class <REPLACE_END> <REPLACE_OLD> item

class <REPLACE_NEW> item

class <REPLACE_END> <INSERT>        if not os.path.isdir(path):
            os.makedirs(path)
 <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html

import json,os
from datetime import datetime
from scrapy.exporters import JsonLinesItemExporter

path = "downloads"

class OnlineparticipationdatasetPipeline(object):
    def process_item(self, item, spider):
        return item

class JsonWriterPipeline(object):

    def open_spider(self, spider):
        if not os.path.isdir(path):
            os.makedirs(path)
        self.file = open("downloads/items_"+spider.name+".json", 'wb')
        self.exporter = JsonLinesItemExporter(self.file, encoding='utf-8', ensure_ascii=False)
        self.exporter.start_exporting()

    def close_spider(self, spider):
        self.exporter.finish_exporting()
        self.file.close()

    def process_item(self, item, spider):
        self.exporter.export_item(item)
        return item

Prompt:
Create path if it doesnt exists

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

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html

import json
from datetime import datetime
from scrapy.exporters import JsonLinesItemExporter

class OnlineparticipationdatasetPipeline(object):
    def process_item(self, item, spider):
        return item

class JsonWriterPipeline(object):

    def open_spider(self, spider):
        self.file = open("downloads/items_"+spider.name+".json", 'wb')
        self.exporter = JsonLinesItemExporter(self.file, encoding='utf-8', ensure_ascii=False)
        self.exporter.start_exporting()

    def close_spider(self, spider):
        self.exporter.finish_exporting()
        self.file.close()

    def process_item(self, item, spider):
        self.exporter.export_item(item)
        return item


# -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.conf import settings
from views import email_add, email_list, email_delete, \
            email_send_activation, email_activate, email_make_primary

#add an email to a User account
urlpatterns = patterns('',
    url(
        r'^email/add/$',
        email_add,
        name='emailmgr_email_add'
        ),
    url(
        r'^email/send_activation/(?P<identifier>\w+)/$',
        email_send_activation,
        name='emailmgr_email_send_activation'
        ),
    url(
        r'^email/activate/(?P<identifier>\w+)/$',
        email_activate,
        name='emailmgr_email_activate'
        ),
    url(
        r'^email/make_primary/(?P<identifier>\w+)/$',
        email_make_primary,
        name='emailmgr_email_make_primary'
        ),
    url(
        r'^email/delete/(?P<identifier>\w+)/$',
        email_delete,
        name='emailmgr_email_delete'
        ),
    url(
        r'^email/$',
        email_list,
        name='emailmgr_email_list'
        ),
)

Fix import for django 1.6

Fix import for django 1.6

Response:
<REPLACE_OLD> django.conf.urls.defaults <REPLACE_NEW> django.conf.urls <REPLACE_END> <REPLACE_OLD> ),
) <REPLACE_NEW> ),
)
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.conf import settings
from views import email_add, email_list, email_delete, \
            email_send_activation, email_activate, email_make_primary

#add an email to a User account
urlpatterns = patterns('',
    url(
        r'^email/add/$',
        email_add,
        name='emailmgr_email_add'
        ),
    url(
        r'^email/send_activation/(?P<identifier>\w+)/$',
        email_send_activation,
        name='emailmgr_email_send_activation'
        ),
    url(
        r'^email/activate/(?P<identifier>\w+)/$',
        email_activate,
        name='emailmgr_email_activate'
        ),
    url(
        r'^email/make_primary/(?P<identifier>\w+)/$',
        email_make_primary,
        name='emailmgr_email_make_primary'
        ),
    url(
        r'^email/delete/(?P<identifier>\w+)/$',
        email_delete,
        name='emailmgr_email_delete'
        ),
    url(
        r'^email/$',
        email_list,
        name='emailmgr_email_list'
        ),
)

Prompt:
Fix import for django 1.6
# -*- coding: utf-8 -*-
from django.conf.urls.defaults import patterns, include, url
from django.conf import settings
from views import email_add, email_list, email_delete, \
            email_send_activation, email_activate, email_make_primary

#add an email to a User account
urlpatterns = patterns('',
    url(
        r'^email/add/$',
        email_add,
        name='emailmgr_email_add'
        ),
    url(
        r'^email/send_activation/(?P<identifier>\w+)/$',
        email_send_activation,
        name='emailmgr_email_send_activation'
        ),
    url(
        r'^email/activate/(?P<identifier>\w+)/$',
        email_activate,
        name='emailmgr_email_activate'
        ),
    url(
        r'^email/make_primary/(?P<identifier>\w+)/$',
        email_make_primary,
        name='emailmgr_email_make_primary'
        ),
    url(
        r'^email/delete/(?P<identifier>\w+)/$',
        email_delete,
        name='emailmgr_email_delete'
        ),
    url(
        r'^email/$',
        email_list,
        name='emailmgr_email_list'
        ),
)


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

from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required

@login_required(login_url='/control/auth/login/')
def index(request):
    return HttpResponseRedirect("/control/events/")

@login_required(login_url='/control/auth/login/')
def eventchange(request, event_id):
    # Get redirect path
    if 'r' in request.GET:
        r = request.GET['r']
        if r[0] != "/":
            r = "/control/"
    else:
        r = "/control/"

    # Set session variable
    try:
        request.session['m_event_id'] = int(event_id)
    except:
        raise Http404

    # Redirect
    return HttpResponseRedirect(r)

Response:
<REPLACE_OLD> HttpResponseRedirect("/control/files/")
 <REPLACE_NEW> HttpResponseRedirect("/control/events/")
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-

from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required

@login_required(login_url='/control/auth/login/')
def index(request):
    return HttpResponseRedirect("/control/events/")

@login_required(login_url='/control/auth/login/')
def eventchange(request, event_id):
    # Get redirect path
    if 'r' in request.GET:
        r = request.GET['r']
        if r[0] != "/":
            r = "/control/"
    else:
        r = "/control/"

    # Set session variable
    try:
        request.session['m_event_id'] = int(event_id)
    except:
        raise Http404

    # Redirect
    return HttpResponseRedirect(r)

Prompt:
admin_base: Fix default refirect when url is /control/

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

from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required

@login_required(login_url='/control/auth/login/')
def index(request):
    return HttpResponseRedirect("/control/files/")

@login_required(login_url='/control/auth/login/')
def eventchange(request, event_id):
    # Get redirect path
    if 'r' in request.GET:
        r = request.GET['r']
        if r[0] != "/":
            r = "/control/"
    else:
        r = "/control/"

    # Set session variable
    try:
        request.session['m_event_id'] = int(event_id)
    except:
        raise Http404

    # Redirect
    return HttpResponseRedirect(r)