import sys
import os

from os.path import join
from setuptools import setup

# Also in twarc.py
__version__ = '1.4.0'

if sys.version_info[0] < 3:
    dependencies = open(join('requirements', 'python2.txt')).read().split()
else:
    dependencies = open(join('requirements', 'python3.txt')).read().split()

if __name__ == "__main__":
    setup(
        name='twarc',
        version=__version__,
        url='https://github.com/docnow/twarc',
        author='Ed Summers',
        author_email='ehs@pobox.com',
        packages=['twarc',],
        description='Archive tweets from the command line',
        python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*',
        install_requires=dependencies,
        setup_requires=['pytest-runner'],
        tests_require=['pytest'],
        entry_points={'console_scripts': ['twarc = twarc:main']}
    )

Add python_requires to help pip

Response:
<INSERT> python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*',
        <INSERT_END> <|endoftext|> import sys
import os

from os.path import join
from setuptools import setup

# Also in twarc.py
__version__ = '1.4.0'

if sys.version_info[0] < 3:
    dependencies = open(join('requirements', 'python2.txt')).read().split()
else:
    dependencies = open(join('requirements', 'python3.txt')).read().split()

if __name__ == "__main__":
    setup(
        name='twarc',
        version=__version__,
        url='https://github.com/docnow/twarc',
        author='Ed Summers',
        author_email='ehs@pobox.com',
        packages=['twarc',],
        description='Archive tweets from the command line',
        python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*',
        install_requires=dependencies,
        setup_requires=['pytest-runner'],
        tests_require=['pytest'],
        entry_points={'console_scripts': ['twarc = twarc:main']}
    )

Prompt:
Add python_requires to help pip

When old Python versions are dropped, this will help pip install the right version for people still running those old Python versions.

For more info on how this works:
* https://hackernoon.com/phasing-out-python-runtimes-gracefully-956f112f33c4
* https://github.com/pypa/python-packaging-user-guide/issues/450
import sys
import os

from os.path import join
from setuptools import setup

# Also in twarc.py
__version__ = '1.4.0'

if sys.version_info[0] < 3:
    dependencies = open(join('requirements', 'python2.txt')).read().split()
else:
    dependencies = open(join('requirements', 'python3.txt')).read().split()

if __name__ == "__main__":
    setup(
        name='twarc',
        version=__version__,
        url='https://github.com/docnow/twarc',
        author='Ed Summers',
        author_email='ehs@pobox.com',
        packages=['twarc',],
        description='Archive tweets from the command line',
        install_requires=dependencies,
        setup_requires=['pytest-runner'],
        tests_require=['pytest'],
        entry_points={'console_scripts': ['twarc = twarc:main']}
    )


#!/usr/bin/python
# Copyright (c) 2010 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import unittest

from pyauto import PyUITest

class SimpleTest(PyUITest):

  def testCanOpenGoogle(self):
    self.NavigateToURL("http://www.google.com")

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

Create a placeholder for pyauto test scripts.

Including a hello world script.

Review URL: http://codereview.chromium.org/668004

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@40579 0039d316-1c4b-4281-b951-d872f2087c98

Response:
<INSERT> #!/usr/bin/python
# Copyright (c) 2010 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import unittest

from pyauto import PyUITest

class SimpleTest(PyUITest):

 <INSERT_END> <INSERT> def testCanOpenGoogle(self):
    self.NavigateToURL("http://www.google.com")

if __name__ == '__main__':
  unittest.main()
 <INSERT_END> <|endoftext|> #!/usr/bin/python
# Copyright (c) 2010 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import unittest

from pyauto import PyUITest

class SimpleTest(PyUITest):

  def testCanOpenGoogle(self):
    self.NavigateToURL("http://www.google.com")

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

Prompt:
Create a placeholder for pyauto test scripts.

Including a hello world script.

Review URL: http://codereview.chromium.org/668004

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@40579 0039d316-1c4b-4281-b951-d872f2087c98


import unittest
from flask import Flask
from flask_json import json_response, FlaskJSON, JsonTestResponse

def our_app():
    app = Flask(__name__)
    app.test_value = 0
    FlaskJSON(app)

    @app.route('/increment')
    def increment():
        app.test_value += 1
        return json_response(value=app.test_value)

    return app

class OurAppTestCase(unittest.TestCase):
    def setUp(self):
        self.app = our_app()
        self.app.config['TESTING'] = True

        # We have to change response class manually since TESTING flag is
        # set after Flask-JSON initialization.
        self.app.response_class = JsonTestResponse
        self.client = self.app.test_client()

    def test_app(self):
        r = self.client.get('/increment')

        # Here is how we can access to JSON.
        assert 'value' in r.json
        assert r.json['value'] == 1

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

Add example usage of the JsonTestResponse.

Response:
<INSERT> import unittest
from flask import Flask
from flask_json import json_response, FlaskJSON, JsonTestResponse

def our_app():
 <INSERT_END> <INSERT>   app = Flask(__name__)
    app.test_value = 0
    FlaskJSON(app)

    @app.route('/increment')
    def increment():
        app.test_value += 1
        return json_response(value=app.test_value)

    return app

class OurAppTestCase(unittest.TestCase):
    def setUp(self):
        self.app = our_app()
        self.app.config['TESTING'] = True

        # We have to change response class manually since TESTING flag is
        # set after Flask-JSON initialization.
        self.app.response_class = JsonTestResponse
        self.client = self.app.test_client()

    def test_app(self):
        r = self.client.get('/increment')

        # Here is how we can access to JSON.
        assert 'value' in r.json
        assert r.json['value'] == 1

if __name__ == '__main__':
    unittest.main()
 <INSERT_END> <|endoftext|> import unittest
from flask import Flask
from flask_json import json_response, FlaskJSON, JsonTestResponse

def our_app():
    app = Flask(__name__)
    app.test_value = 0
    FlaskJSON(app)

    @app.route('/increment')
    def increment():
        app.test_value += 1
        return json_response(value=app.test_value)

    return app

class OurAppTestCase(unittest.TestCase):
    def setUp(self):
        self.app = our_app()
        self.app.config['TESTING'] = True

        # We have to change response class manually since TESTING flag is
        # set after Flask-JSON initialization.
        self.app.response_class = JsonTestResponse
        self.client = self.app.test_client()

    def test_app(self):
        r = self.client.get('/increment')

        # Here is how we can access to JSON.
        assert 'value' in r.json
        assert r.json['value'] == 1

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

Prompt: Add example usage of the JsonTestResponse.


from .affine import Affine
from ... import describe
from ...describe import Dimension, Synapses, Biases
from ...check import has_shape
from ... import check

@describe.attributes(
    W=Synapses("Weights matrix",
        lambda obj: (obj.nO, obj.nI),
        lambda W, ops: None)
)
class Softmax(Affine):
    name = 'softmax'
    @check.arg(1, has_shape(('nB', 'nI')))
    def predict(self, input__BI):
        output__BO = self.ops.affine(self.W, self.b, input__BI)
        output__BO = self.ops.softmax(output__BO, inplace=False)
        return output__BO

    @check.arg(1, has_shape(('nB', 'nI')))
    def begin_update(self, input__BI, drop=0.):
        output__BO = self.predict(input__BI)
        @check.arg(0, has_shape(('nB', 'nO')))
        def finish_update(grad__BO, sgd=None):
            self.d_W += self.ops.gemm(grad__BO, input__BI, trans1=True)
            self.d_b += grad__BO.sum(axis=0)
            grad__BI = self.ops.gemm(grad__BO, self.W)
            if sgd is not None:
                sgd(self._mem.weights, self._mem.gradient, key=self.id)
            return grad__BI
        return output__BO, finish_update

Fix gemm calls in Softmax

Fix gemm calls in Softmax

Response:
<REPLACE_OLD> self.ops.batch_outer(grad__BO, input__BI)
 <REPLACE_NEW> self.ops.gemm(grad__BO, input__BI, trans1=True)
 <REPLACE_END> <REPLACE_OLD> self.ops.dot(grad__BO, <REPLACE_NEW> self.ops.gemm(grad__BO, <REPLACE_END> <|endoftext|> from .affine import Affine
from ... import describe
from ...describe import Dimension, Synapses, Biases
from ...check import has_shape
from ... import check

@describe.attributes(
    W=Synapses("Weights matrix",
        lambda obj: (obj.nO, obj.nI),
        lambda W, ops: None)
)
class Softmax(Affine):
    name = 'softmax'
    @check.arg(1, has_shape(('nB', 'nI')))
    def predict(self, input__BI):
        output__BO = self.ops.affine(self.W, self.b, input__BI)
        output__BO = self.ops.softmax(output__BO, inplace=False)
        return output__BO

    @check.arg(1, has_shape(('nB', 'nI')))
    def begin_update(self, input__BI, drop=0.):
        output__BO = self.predict(input__BI)
        @check.arg(0, has_shape(('nB', 'nO')))
        def finish_update(grad__BO, sgd=None):
            self.d_W += self.ops.gemm(grad__BO, input__BI, trans1=True)
            self.d_b += grad__BO.sum(axis=0)
            grad__BI = self.ops.gemm(grad__BO, self.W)
            if sgd is not None:
                sgd(self._mem.weights, self._mem.gradient, key=self.id)
            return grad__BI
        return output__BO, finish_update

Prompt:
Fix gemm calls in Softmax

from .affine import Affine
from ... import describe
from ...describe import Dimension, Synapses, Biases
from ...check import has_shape
from ... import check

@describe.attributes(
    W=Synapses("Weights matrix",
        lambda obj: (obj.nO, obj.nI),
        lambda W, ops: None)
)
class Softmax(Affine):
    name = 'softmax'
    @check.arg(1, has_shape(('nB', 'nI')))
    def predict(self, input__BI):
        output__BO = self.ops.affine(self.W, self.b, input__BI)
        output__BO = self.ops.softmax(output__BO, inplace=False)
        return output__BO

    @check.arg(1, has_shape(('nB', 'nI')))
    def begin_update(self, input__BI, drop=0.):
        output__BO = self.predict(input__BI)
        @check.arg(0, has_shape(('nB', 'nO')))
        def finish_update(grad__BO, sgd=None):
            self.d_W += self.ops.batch_outer(grad__BO, input__BI)
            self.d_b += grad__BO.sum(axis=0)
            grad__BI = self.ops.dot(grad__BO, self.W)
            if sgd is not None:
                sgd(self._mem.weights, self._mem.gradient, key=self.id)
            return grad__BI
        return output__BO, finish_update


from rdflib import ConjunctiveGraph, Literal
from StringIO import StringIO
import unittest

test_data = """
@prefix foaf:       <http://xmlns.com/foaf/0.1/> .
@prefix rdf:        <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .

<http://example.org/alice> a foaf:Person;
    foaf:name "Alice";
    foaf:knows <http://example.org/bob> ."""

test_query = """
BASE <http://xmlns.com/foaf/0.1/>
SELECT ?name
WHERE { [ a :Person; :name ?name ]. }
}"""

class TestSparqlJsonResults(unittest.TestCase):

    def setUp(self):
        self.graph = ConjunctiveGraph()
        self.graph.parse(StringIO(test_data), format="n3")

    def test_base_ref(self):
        rt=self.graph.query(test_query).serialize("python")
        self.failUnless(rt[0] == Literal("Alice"),"Expected:\n 'Alice' \nGot:\n %s" % rt)

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

Test for use of BASE <..>

Test for use of BASE <..>

Response:
<INSERT> from rdflib import ConjunctiveGraph, Literal
from StringIO import StringIO
import unittest

test_data = """
@prefix foaf: <INSERT_END> <INSERT>      <http://xmlns.com/foaf/0.1/> .
@prefix rdf:        <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .

<http://example.org/alice> a foaf:Person;
    foaf:name "Alice";
    foaf:knows <http://example.org/bob> ."""

test_query = """
BASE <http://xmlns.com/foaf/0.1/>
SELECT ?name
WHERE { [ a :Person; :name ?name ]. }
}"""

class TestSparqlJsonResults(unittest.TestCase):

    def setUp(self):
        self.graph = ConjunctiveGraph()
        self.graph.parse(StringIO(test_data), format="n3")

    def test_base_ref(self):
        rt=self.graph.query(test_query).serialize("python")
        self.failUnless(rt[0] == Literal("Alice"),"Expected:\n 'Alice' \nGot:\n %s" % rt)

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

 <INSERT_END> <|endoftext|> from rdflib import ConjunctiveGraph, Literal
from StringIO import StringIO
import unittest

test_data = """
@prefix foaf:       <http://xmlns.com/foaf/0.1/> .
@prefix rdf:        <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .

<http://example.org/alice> a foaf:Person;
    foaf:name "Alice";
    foaf:knows <http://example.org/bob> ."""

test_query = """
BASE <http://xmlns.com/foaf/0.1/>
SELECT ?name
WHERE { [ a :Person; :name ?name ]. }
}"""

class TestSparqlJsonResults(unittest.TestCase):

    def setUp(self):
        self.graph = ConjunctiveGraph()
        self.graph.parse(StringIO(test_data), format="n3")

    def test_base_ref(self):
        rt=self.graph.query(test_query).serialize("python")
        self.failUnless(rt[0] == Literal("Alice"),"Expected:\n 'Alice' \nGot:\n %s" % rt)

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

Prompt: Test for use of BASE <..>


from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.shortcuts import render

from wagtail.core.models import Page
from wagtail.search.models import Query

def search(request):
    search_query = request.GET.get('q', None)
    page = request.GET.get('page', 1)

    # Search
    if search_query:
        search_results = Page.objects.live().search(search_query)
        query = Query.get(search_query)

        # Record hit
        query.add_hit()
    else:
        search_results = Page.objects.none()

    # Pagination
    paginator = Paginator(search_results, 10)
    try:
        search_results = paginator.page(page)
    except PageNotAnInteger:
        search_results = paginator.page(1)
    except EmptyPage:
        search_results = paginator.page(paginator.num_pages)

    return render(request, 'search/search.html', {
        'search_query': search_query,
        'search_results': search_results,
    })

Response:
<REPLACE_OLD> request.GET.get('query', <REPLACE_NEW> request.GET.get('q', <REPLACE_END> <|endoftext|> from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.shortcuts import render

from wagtail.core.models import Page
from wagtail.search.models import Query

def search(request):
    search_query = request.GET.get('q', None)
    page = request.GET.get('page', 1)

    # Search
    if search_query:
        search_results = Page.objects.live().search(search_query)
        query = Query.get(search_query)

        # Record hit
        query.add_hit()
    else:
        search_results = Page.objects.none()

    # Pagination
    paginator = Paginator(search_results, 10)
    try:
        search_results = paginator.page(page)
    except PageNotAnInteger:
        search_results = paginator.page(1)
    except EmptyPage:
        search_results = paginator.page(paginator.num_pages)

    return render(request, 'search/search.html', {
        'search_query': search_query,
        'search_results': search_results,
    })

Prompt:
Make search parameter match template parameter name
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.shortcuts import render

from wagtail.core.models import Page
from wagtail.search.models import Query

def search(request):
    search_query = request.GET.get('query', None)
    page = request.GET.get('page', 1)

    # Search
    if search_query:
        search_results = Page.objects.live().search(search_query)
        query = Query.get(search_query)

        # Record hit
        query.add_hit()
    else:
        search_results = Page.objects.none()

    # Pagination
    paginator = Paginator(search_results, 10)
    try:
        search_results = paginator.page(page)
    except PageNotAnInteger:
        search_results = paginator.page(1)
    except EmptyPage:
        search_results = paginator.page(paginator.num_pages)

    return render(request, 'search/search.html', {
        'search_query': search_query,
        'search_results': search_results,
    })


import logging
import re
import socket
import urllib
from bs4 import BeautifulSoup

logger = logging.getLogger(__name__)
WURSTBALL_RE = re.compile("^http[s]://wurstball.de/[0-9]+/")

def default_handler(metadata):
    return {key: getattr(metadata, key) for key in
            ["original_url", "url", "title", "description",
             "human_readable_type"]}

def wurstball_handler(metadata):
    if WURSTBALL_RE.match(metadata.url) is None:
        return None

    ret = default_handler(metadata)

    soup = BeautifulSoup(metadata.buf)
    img_url = soup.find(id="content-main").img["src"]

    try:
        response = urllib.request.urlopen(img_url, timeout=5)
        img_data = response.read()
    except (socket.timeout,
            urllib.error.URLError,
            urllib.error.HTTPError) as err:
        logger.warn("Could not download Wurstball image: {}".format(err))
        return ret

    mime_type = response.getheader("Content-Type")

    ret.update({"image_mime_type": mime_type,
                "image_buffer": img_data,
                "image_url": img_url})

    return ret

Response:
<INSERT> logging
import <INSERT_END> <REPLACE_OLD> BeautifulSoup

WURSTBALL_RE <REPLACE_NEW> BeautifulSoup

logger = logging.getLogger(__name__)
WURSTBALL_RE <REPLACE_END> <REPLACE_OLD> urllib.error.HTTPError):
 <REPLACE_NEW> urllib.error.HTTPError) as err:
        logger.warn("Could not download Wurstball image: {}".format(err))
 <REPLACE_END> <|endoftext|> import logging
import re
import socket
import urllib
from bs4 import BeautifulSoup

logger = logging.getLogger(__name__)
WURSTBALL_RE = re.compile("^http[s]://wurstball.de/[0-9]+/")

def default_handler(metadata):
    return {key: getattr(metadata, key) for key in
            ["original_url", "url", "title", "description",
             "human_readable_type"]}

def wurstball_handler(metadata):
    if WURSTBALL_RE.match(metadata.url) is None:
        return None

    ret = default_handler(metadata)

    soup = BeautifulSoup(metadata.buf)
    img_url = soup.find(id="content-main").img["src"]

    try:
        response = urllib.request.urlopen(img_url, timeout=5)
        img_data = response.read()
    except (socket.timeout,
            urllib.error.URLError,
            urllib.error.HTTPError) as err:
        logger.warn("Could not download Wurstball image: {}".format(err))
        return ret

    mime_type = response.getheader("Content-Type")

    ret.update({"image_mime_type": mime_type,
                "image_buffer": img_data,
                "image_url": img_url})

    return ret

Prompt:
Print warning when wurstball downloads fail

import re
import socket
import urllib
from bs4 import BeautifulSoup

WURSTBALL_RE = re.compile("^http[s]://wurstball.de/[0-9]+/")

def default_handler(metadata):
    return {key: getattr(metadata, key) for key in
            ["original_url", "url", "title", "description",
             "human_readable_type"]}

def wurstball_handler(metadata):
    if WURSTBALL_RE.match(metadata.url) is None:
        return None

    ret = default_handler(metadata)

    soup = BeautifulSoup(metadata.buf)
    img_url = soup.find(id="content-main").img["src"]

    try:
        response = urllib.request.urlopen(img_url, timeout=5)
        img_data = response.read()
    except (socket.timeout,
            urllib.error.URLError,
            urllib.error.HTTPError):
        return ret

    mime_type = response.getheader("Content-Type")

    ret.update({"image_mime_type": mime_type,
                "image_buffer": img_data,
                "image_url": img_url})

    return ret


# 3-4 Guest List

guest_list = ["Albert Einstein", "Isac Newton", "Marie Curie", "Galileo Galilei"]

message = "Hi " + guest_list[0] + " you are invited to dinner at 7 on saturday."
print(message)

message = "Hi " + guest_list[1] + " you are invited to dinner at 7 on saturday."
print(message)

message = "Hi " + guest_list[2] + " you are invited to dinner at 7 on saturday."
print(message)

message = "Hi " + guest_list[3] + " you are invited to dinner at 7 on saturday."
print(message)

Add solution to exercise 4.4.

Add solution to exercise 4.4.

Response:
<REPLACE_OLD>  <REPLACE_NEW> # 3-4 Guest List

guest_list = ["Albert Einstein", "Isac Newton", "Marie Curie", "Galileo Galilei"]

message = "Hi " + guest_list[0] + " you are invited to dinner at 7 on saturday."
print(message)

message = "Hi " + guest_list[1] + " you are invited to dinner at 7 on saturday."
print(message)

message = "Hi " + guest_list[2] + " you are invited to dinner at 7 on saturday."
print(message)

message = "Hi " + guest_list[3] + " you are invited to dinner at 7 on saturday."
print(message)
 <REPLACE_END> <|endoftext|> # 3-4 Guest List

guest_list = ["Albert Einstein", "Isac Newton", "Marie Curie", "Galileo Galilei"]

message = "Hi " + guest_list[0] + " you are invited to dinner at 7 on saturday."
print(message)

message = "Hi " + guest_list[1] + " you are invited to dinner at 7 on saturday."
print(message)

message = "Hi " + guest_list[2] + " you are invited to dinner at 7 on saturday."
print(message)

message = "Hi " + guest_list[3] + " you are invited to dinner at 7 on saturday."
print(message)

Prompt: Add solution to exercise 4.4.


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

# Import Python libs
from __future__ import absolute_import
import time

# Import Salt libs
import salt.utils.decorators

def _fallbackfunc():
    return False, 'fallback'

def working_function():
    '''
    CLI Example:

    .. code-block:: bash
    '''
    return True

@salt.utils.decorators.depends(True)
def booldependsTrue():
    '''
    CLI Example:

    .. code-block:: bash
    '''
    return True

@salt.utils.decorators.depends(False)
def booldependsFalse():
    return True

@salt.utils.decorators.depends('time')
def depends():
    ret = {'ret': True,
           'time': time.time()}
    return ret

@salt.utils.decorators.depends('time123')
def missing_depends():
    return True

@salt.utils.decorators.depends('time', fallback_function=_fallbackfunc)
def depends_will_not_fallback():
    '''
    CLI Example:

    .. code-block:: bash
    '''
    ret = {'ret': True,
           'time': time.time()}
    return ret

@salt.utils.decorators.depends('time123', fallback_function=_fallbackfunc)
def missing_depends_will_fallback():
    ret = {'ret': True,
           'time': time.time()}
    return ret

Response:
<REPLACE_OLD> True

@salt.utils.decorators.depends(True)
def <REPLACE_NEW> True

@salt.utils.decorators.depends(True)
def <REPLACE_END> <REPLACE_OLD> True

@salt.utils.decorators.depends(False)
def <REPLACE_NEW> True

@salt.utils.decorators.depends(False)
def <REPLACE_END> <REPLACE_OLD> True

@salt.utils.decorators.depends('time')
def <REPLACE_NEW> True

@salt.utils.decorators.depends('time')
def <REPLACE_END> <INSERT>    '''
    CLI Example:

    .. code-block:: bash
    '''
 <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-

# Import Python libs
from __future__ import absolute_import
import time

# Import Salt libs
import salt.utils.decorators

def _fallbackfunc():
    return False, 'fallback'

def working_function():
    '''
    CLI Example:

    .. code-block:: bash
    '''
    return True

@salt.utils.decorators.depends(True)
def booldependsTrue():
    '''
    CLI Example:

    .. code-block:: bash
    '''
    return True

@salt.utils.decorators.depends(False)
def booldependsFalse():
    return True

@salt.utils.decorators.depends('time')
def depends():
    ret = {'ret': True,
           'time': time.time()}
    return ret

@salt.utils.decorators.depends('time123')
def missing_depends():
    return True

@salt.utils.decorators.depends('time', fallback_function=_fallbackfunc)
def depends_will_not_fallback():
    '''
    CLI Example:

    .. code-block:: bash
    '''
    ret = {'ret': True,
           'time': time.time()}
    return ret

@salt.utils.decorators.depends('time123', fallback_function=_fallbackfunc)
def missing_depends_will_fallback():
    ret = {'ret': True,
           'time': time.time()}
    return ret

Prompt:
Fix tests: add module function docstring

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

# Import Python libs
from __future__ import absolute_import
import time

# Import Salt libs
import salt.utils.decorators

def _fallbackfunc():
    return False, 'fallback'

def working_function():
    '''
    CLI Example:

    .. code-block:: bash
    '''
    return True

@salt.utils.decorators.depends(True)
def booldependsTrue():
    '''
    CLI Example:

    .. code-block:: bash
    '''
    return True

@salt.utils.decorators.depends(False)
def booldependsFalse():
    return True

@salt.utils.decorators.depends('time')
def depends():
    ret = {'ret': True,
           'time': time.time()}
    return ret

@salt.utils.decorators.depends('time123')
def missing_depends():
    return True

@salt.utils.decorators.depends('time', fallback_function=_fallbackfunc)
def depends_will_not_fallback():
    ret = {'ret': True,
           'time': time.time()}
    return ret

@salt.utils.decorators.depends('time123', fallback_function=_fallbackfunc)
def missing_depends_will_fallback():
    ret = {'ret': True,
           'time': time.time()}
    return ret


import pygame

class Graphic:
    car_color = (255, 50, 50)
    car_width = 3
    road_color = (255, 255, 255)
    road_width = 6
    draw_methods = {
        'Car': 'draw_car',
        'Road': 'draw_road',
    }

    def __init__(self, surface):
        self.surface = surface

    def draw(self, obj):
        object_class = obj.__class__.__name__
        method_name = self.draw_methods.get(object_class, None)
        if method_name:
            method = getattr(self, method_name)
            method(obj)

    def draw_car(self, car):
        coord = car.coordinates
        acceleration_rate = car.acceleration_rate
        rect = pygame.Rect(coord.x, coord.y,
                           self.car_width, self.car_width)

        # Change car color depending on acceleration
        if acceleration_rate > 0:
            color = (0, 0, 255)
        else:
            color = (255, 0, 0)
        pygame.draw.rect(self.surface, color, rect, 0)

    def draw_road(self, road):
        pointlist = road.pointlist()
        closed = False
        pygame.draw.lines(self.surface, self.road_color, closed, pointlist,
                          self.road_width)

Make color easier to read

Make color easier to read

Response:
<DELETE> rate = min(1, acceleration_rate)
            <DELETE_END> <REPLACE_OLD> int(rate * 255))
 <REPLACE_NEW> 255)
 <REPLACE_END> <DELETE> rate = max(-1, acceleration_rate)
            <DELETE_END> <REPLACE_OLD> (int(-rate * 255), <REPLACE_NEW> (255, <REPLACE_END> <|endoftext|> import pygame

class Graphic:
    car_color = (255, 50, 50)
    car_width = 3
    road_color = (255, 255, 255)
    road_width = 6
    draw_methods = {
        'Car': 'draw_car',
        'Road': 'draw_road',
    }

    def __init__(self, surface):
        self.surface = surface

    def draw(self, obj):
        object_class = obj.__class__.__name__
        method_name = self.draw_methods.get(object_class, None)
        if method_name:
            method = getattr(self, method_name)
            method(obj)

    def draw_car(self, car):
        coord = car.coordinates
        acceleration_rate = car.acceleration_rate
        rect = pygame.Rect(coord.x, coord.y,
                           self.car_width, self.car_width)

        # Change car color depending on acceleration
        if acceleration_rate > 0:
            color = (0, 0, 255)
        else:
            color = (255, 0, 0)
        pygame.draw.rect(self.surface, color, rect, 0)

    def draw_road(self, road):
        pointlist = road.pointlist()
        closed = False
        pygame.draw.lines(self.surface, self.road_color, closed, pointlist,
                          self.road_width)

Prompt:
Make color easier to read

import pygame

class Graphic:
    car_color = (255, 50, 50)
    car_width = 3
    road_color = (255, 255, 255)
    road_width = 6
    draw_methods = {
        'Car': 'draw_car',
        'Road': 'draw_road',
    }

    def __init__(self, surface):
        self.surface = surface

    def draw(self, obj):
        object_class = obj.__class__.__name__
        method_name = self.draw_methods.get(object_class, None)
        if method_name:
            method = getattr(self, method_name)
            method(obj)

    def draw_car(self, car):
        coord = car.coordinates
        acceleration_rate = car.acceleration_rate
        rect = pygame.Rect(coord.x, coord.y,
                           self.car_width, self.car_width)

        # Change car color depending on acceleration
        if acceleration_rate > 0:
            rate = min(1, acceleration_rate)
            color = (0, 0, int(rate * 255))
        else:
            rate = max(-1, acceleration_rate)
            color = (int(-rate * 255), 0, 0)
        pygame.draw.rect(self.surface, color, rect, 0)

    def draw_road(self, road):
        pointlist = road.pointlist()
        closed = False
        pygame.draw.lines(self.surface, self.road_color, closed, pointlist,
                          self.road_width)


import os
import commands
import time
import logging
import sys

if len(sys.argv) != 3 or (sys.argv[1:][0] not in ['pt', 'en']):
    print "ERROR! Use:\n python scripts/data_download/rais/create_files.py en/pt output_path\n"
    exit()

logging.basicConfig(filename=os.path.abspath(os.path.join(sys.argv[2],str(sys.argv[0].split('/')[2]) + '-all-data-download.log' )),level=logging.DEBUG)

for year in range(2002, 2015):
    logging.info("python scripts/data_download/rais/create_files.py "+str(sys.argv[1])+" "+str(sys.argv[2])+" "+ str(year) + "\n")
    ret = commands.getoutput("python scripts/data_download/rais/create_files.py "+str(sys.argv[1])+" "+str(sys.argv[2])+" "+ str(year))
    logging.info(str(ret) + "\nYear: " + str(year) + " ok =D\n\n")

Add file to create all files to rais.

Add file to create all files to rais.

Response:
<INSERT> import os
import commands
import time
import logging
import sys

if len(sys.argv) != 3 or (sys.argv[1:][0] not in ['pt', 'en']):
 <INSERT_END> <INSERT>   print "ERROR! Use:\n python scripts/data_download/rais/create_files.py en/pt output_path\n"
    exit()

logging.basicConfig(filename=os.path.abspath(os.path.join(sys.argv[2],str(sys.argv[0].split('/')[2]) + '-all-data-download.log' )),level=logging.DEBUG)

for year in range(2002, 2015):
    logging.info("python scripts/data_download/rais/create_files.py "+str(sys.argv[1])+" "+str(sys.argv[2])+" "+ str(year) + "\n")
    ret = commands.getoutput("python scripts/data_download/rais/create_files.py "+str(sys.argv[1])+" "+str(sys.argv[2])+" "+ str(year))
    logging.info(str(ret) + "\nYear: " + str(year) + " ok =D\n\n") <INSERT_END> <|endoftext|> import os
import commands
import time
import logging
import sys

if len(sys.argv) != 3 or (sys.argv[1:][0] not in ['pt', 'en']):
    print "ERROR! Use:\n python scripts/data_download/rais/create_files.py en/pt output_path\n"
    exit()

logging.basicConfig(filename=os.path.abspath(os.path.join(sys.argv[2],str(sys.argv[0].split('/')[2]) + '-all-data-download.log' )),level=logging.DEBUG)

for year in range(2002, 2015):
    logging.info("python scripts/data_download/rais/create_files.py "+str(sys.argv[1])+" "+str(sys.argv[2])+" "+ str(year) + "\n")
    ret = commands.getoutput("python scripts/data_download/rais/create_files.py "+str(sys.argv[1])+" "+str(sys.argv[2])+" "+ str(year))
    logging.info(str(ret) + "\nYear: " + str(year) + " ok =D\n\n")

Prompt: Add file to create all files to rais.


"""
DataTransformer

:Authors:
	Berend Klein Haneveld
"""

from vtk import vtkImageReslice

class DataTransformer(object):
	"""DataTransformer is a class that can transform a given dataset"""
	def __init__(self):
		super(DataTransformer, self).__init__()

	def TransformImageData(self, imageData, transform):
		"""
		:type imageData: vtkImageData
		:type transform: vtkTransform
		"""
		reslicer = vtkImageReslice()
		reslicer.SetInterpolationModeToCubic()
		reslicer.SetAutoCropOutput(1)  # Not sure if this is what we want

		reslicer.SetInputData(imageData)
		reslicer.SetResliceTransform(transform.GetInverse())

		return reslicer.GetOutput()

Add a simple transform helper class.

Add a simple transform helper class.

Response:
<INSERT> """
DataTransformer

:Authors:
	Berend Klein Haneveld
"""

from vtk import vtkImageReslice

class DataTransformer(object):
	"""DataTransformer is a class that can transform a given dataset"""
	def __init__(self):
		super(DataTransformer, self).__init__()

	def TransformImageData(self, imageData, transform):
		"""
		:type imageData: vtkImageData
		:type transform: vtkTransform
		"""
		reslicer = vtkImageReslice()
		reslicer.SetInterpolationModeToCubic()
		reslicer.SetAutoCropOutput(1) <INSERT_END> <INSERT> # Not sure if this is what we want

		reslicer.SetInputData(imageData)
		reslicer.SetResliceTransform(transform.GetInverse())

		return reslicer.GetOutput()
 <INSERT_END> <|endoftext|> """
DataTransformer

:Authors:
	Berend Klein Haneveld
"""

from vtk import vtkImageReslice

class DataTransformer(object):
	"""DataTransformer is a class that can transform a given dataset"""
	def __init__(self):
		super(DataTransformer, self).__init__()

	def TransformImageData(self, imageData, transform):
		"""
		:type imageData: vtkImageData
		:type transform: vtkTransform
		"""
		reslicer = vtkImageReslice()
		reslicer.SetInterpolationModeToCubic()
		reslicer.SetAutoCropOutput(1)  # Not sure if this is what we want

		reslicer.SetInputData(imageData)
		reslicer.SetResliceTransform(transform.GetInverse())

		return reslicer.GetOutput()

Prompt: Add a simple transform helper class.


# -*- coding: utf-8 -*-
import unittest

from bitbucket.bitbucket import Bitbucket
from bitbucket.tests.private import USERNAME, PASSWORD

TEST_REPO_SLUG = 'test_bitbucket_api'

class AuthenticatedBitbucketTest(unittest.TestCase):
    """ Bitbucket test base class for authenticated methods."""
    def setUp(self):
        """Creating a new authenticated Bitbucket..."""
        self.bb = Bitbucket(USERNAME, PASSWORD)
        # Create a repository.
        success, result = self.bb.repository.create(TEST_REPO_SLUG, has_issues=True)
        # Save repository's id
        assert success
        self.bb.repo_slug = result[u'slug']

    def tearDown(self):
        """Destroying the Bitbucket..."""
        # Delete the repository.
        self.bb.repository.delete()
        self.bb = None

class BitbucketAuthenticatedMethodsTest(AuthenticatedBitbucketTest):
    """ Testing Bitbucket annonymous methods."""

    def test_get_tags(self):
        """ Test get_tags."""
        success, result = self.bb.get_tags()
        self.assertTrue(success)
        self.assertIsInstance(result, dict)
        # test with invalid repository name
        success, result = self.bb.get_tags(repo_slug='azertyuiop')
        self.assertFalse(success)

    def test_get_branches(self):
        """ Test get_branches."""
        success, result = self.bb.get_branches()
        self.assertTrue(success)
        self.assertIsInstance(result, dict)
        # test with invalid repository name
        success, result = self.bb.get_branches(repo_slug='azertyuiop')
        self.assertFalse(success)

Response:
<REPLACE_OLD> dict)

 <REPLACE_NEW> dict)
        # test with invalid repository name
        success, result = self.bb.get_tags(repo_slug='azertyuiop')
        self.assertFalse(success)

 <REPLACE_END> <INSERT>        # test with invalid repository name
        success, result = self.bb.get_branches(repo_slug='azertyuiop')
        self.assertFalse(success)
 <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
import unittest

from bitbucket.bitbucket import Bitbucket
from bitbucket.tests.private import USERNAME, PASSWORD

TEST_REPO_SLUG = 'test_bitbucket_api'

class AuthenticatedBitbucketTest(unittest.TestCase):
    """ Bitbucket test base class for authenticated methods."""
    def setUp(self):
        """Creating a new authenticated Bitbucket..."""
        self.bb = Bitbucket(USERNAME, PASSWORD)
        # Create a repository.
        success, result = self.bb.repository.create(TEST_REPO_SLUG, has_issues=True)
        # Save repository's id
        assert success
        self.bb.repo_slug = result[u'slug']

    def tearDown(self):
        """Destroying the Bitbucket..."""
        # Delete the repository.
        self.bb.repository.delete()
        self.bb = None

class BitbucketAuthenticatedMethodsTest(AuthenticatedBitbucketTest):
    """ Testing Bitbucket annonymous methods."""

    def test_get_tags(self):
        """ Test get_tags."""
        success, result = self.bb.get_tags()
        self.assertTrue(success)
        self.assertIsInstance(result, dict)
        # test with invalid repository name
        success, result = self.bb.get_tags(repo_slug='azertyuiop')
        self.assertFalse(success)

    def test_get_branches(self):
        """ Test get_branches."""
        success, result = self.bb.get_branches()
        self.assertTrue(success)
        self.assertIsInstance(result, dict)
        # test with invalid repository name
        success, result = self.bb.get_branches(repo_slug='azertyuiop')
        self.assertFalse(success)

Prompt:
Update BitbucketAuthenticatedMethodsTest's test_get_tags and test_get_branches methods.

Signed-off-by: Baptiste Millou <1cfd48a9a65a966defdcd720f66cd790094000c4@smoothie-creative.com>

# -*- coding: utf-8 -*-
import unittest

from bitbucket.bitbucket import Bitbucket
from bitbucket.tests.private import USERNAME, PASSWORD

TEST_REPO_SLUG = 'test_bitbucket_api'

class AuthenticatedBitbucketTest(unittest.TestCase):
    """ Bitbucket test base class for authenticated methods."""
    def setUp(self):
        """Creating a new authenticated Bitbucket..."""
        self.bb = Bitbucket(USERNAME, PASSWORD)
        # Create a repository.
        success, result = self.bb.repository.create(TEST_REPO_SLUG, has_issues=True)
        # Save repository's id
        assert success
        self.bb.repo_slug = result[u'slug']

    def tearDown(self):
        """Destroying the Bitbucket..."""
        # Delete the repository.
        self.bb.repository.delete()
        self.bb = None

class BitbucketAuthenticatedMethodsTest(AuthenticatedBitbucketTest):
    """ Testing Bitbucket annonymous methods."""

    def test_get_tags(self):
        """ Test get_tags."""
        success, result = self.bb.get_tags()
        self.assertTrue(success)
        self.assertIsInstance(result, dict)

    def test_get_branches(self):
        """ Test get_branches."""
        success, result = self.bb.get_branches()
        self.assertTrue(success)
        self.assertIsInstance(result, dict)


from django.db import models
from django.contrib.auth.models import User, Group
from evewspace.Map.models import Map
from django.db.models.signals import post_save

# Create your models here.

class PlayTime(models.Model):
	"""PlayTime represents a choice of play times for use in several forms."""
	fromtime = models.TimeField()
	totime = models.TimeField()

class UserProfile(models.Model):
	"""UserProfile defines custom fields tied to each User record in the Django auth DB."""
	user = models.ForeignKey(User, unique = True)
	jabberid = models.EmailField(blank = True, null=True)
	defaultmap = models.ForeignKey(Map, related_name = "defaultusers", blank=True, null=True)
	playtimes = models.ManyToManyField(PlayTime)

class GroupProfile(models.Model):
	"""GroupProfile defines custom fields tied to each Group record."""
	group = models.ForeignKey(Group, unique=True)
	description = models.CharField(max_length=200, blank=True, null=True)

def create_user_profile(sender, instance, created, **kwargs):
	"""Handle user creation event and create a new profile to match the new user"""
	if created:
		UserProfile.objects.create(user=instance)

post_save.connect(create_user_profile, sender=User)

def create_group_profile(sender, instance, created, **kwargs):
	"""Handle group creation even and create a new group profile."""
	if created:
		GroupProfile.objects.create(group=instance)
post_save.connect(create_group_profile, sender=Group)

Response:
<INSERT> PlayTime(models.Model):
	"""PlayTime represents a choice of play times for use in several forms."""
	fromtime = models.TimeField()
	totime = models.TimeField()

class <INSERT_END> <REPLACE_OLD> null=True)

class <REPLACE_NEW> null=True)
	playtimes = models.ManyToManyField(PlayTime)

class <REPLACE_END> <|endoftext|> from django.db import models
from django.contrib.auth.models import User, Group
from evewspace.Map.models import Map
from django.db.models.signals import post_save

# Create your models here.

class PlayTime(models.Model):
	"""PlayTime represents a choice of play times for use in several forms."""
	fromtime = models.TimeField()
	totime = models.TimeField()

class UserProfile(models.Model):
	"""UserProfile defines custom fields tied to each User record in the Django auth DB."""
	user = models.ForeignKey(User, unique = True)
	jabberid = models.EmailField(blank = True, null=True)
	defaultmap = models.ForeignKey(Map, related_name = "defaultusers", blank=True, null=True)
	playtimes = models.ManyToManyField(PlayTime)

class GroupProfile(models.Model):
	"""GroupProfile defines custom fields tied to each Group record."""
	group = models.ForeignKey(Group, unique=True)
	description = models.CharField(max_length=200, blank=True, null=True)

def create_user_profile(sender, instance, created, **kwargs):
	"""Handle user creation event and create a new profile to match the new user"""
	if created:
		UserProfile.objects.create(user=instance)

post_save.connect(create_user_profile, sender=User)

def create_group_profile(sender, instance, created, **kwargs):
	"""Handle group creation even and create a new group profile."""
	if created:
		GroupProfile.objects.create(group=instance)
post_save.connect(create_group_profile, sender=Group)

Prompt:
Add PlayTime class and tie it to user profiles

Created a PlayTime class in account with from and to times.
Added ManyToManyField to UserProfile to keep track of play times.

from django.db import models
from django.contrib.auth.models import User, Group
from evewspace.Map.models import Map
from django.db.models.signals import post_save

# Create your models here.

class UserProfile(models.Model):
	"""UserProfile defines custom fields tied to each User record in the Django auth DB."""
	user = models.ForeignKey(User, unique = True)
	jabberid = models.EmailField(blank = True, null=True)
	defaultmap = models.ForeignKey(Map, related_name = "defaultusers", blank=True, null=True)

class GroupProfile(models.Model):
	"""GroupProfile defines custom fields tied to each Group record."""
	group = models.ForeignKey(Group, unique=True)
	description = models.CharField(max_length=200, blank=True, null=True)

def create_user_profile(sender, instance, created, **kwargs):
	"""Handle user creation event and create a new profile to match the new user"""
	if created:
		UserProfile.objects.create(user=instance)

post_save.connect(create_user_profile, sender=User)

def create_group_profile(sender, instance, created, **kwargs):
	"""Handle group creation even and create a new group profile."""
	if created:
		GroupProfile.objects.create(group=instance)
post_save.connect(create_group_profile, sender=Group)


#!/usr/bin/python
"""An example demonstrating the client-side usage
of the cretificate request API endpoint.
"""

import requests, sys, json

otp = sys.argv[1]

domain_req_url = 'https://spire.cloudfleet.io/api/v1/blimp/domain'
domain_txt_path = '/opt/cloudfleet/data/config/domain.txt'

print('retrieving domain for blimp: ' + domain_req_url)

r = requests.get(domain_req_url, headers={'X-AUTH-OTP': otp})

if r.status_code == 200:
    print('Success: %s' % r.text)
    result_dict = r.json()

    if "domain" in result_dict:
        with open(domain_txt_path, 'w') as domain_txt_file:
            domain_txt_file.write(result_dict['domain'])
        quit(0)
    else:
        quit(1)
else:
    print('Error: %s. Is the OTP correct? Double-check on Spire!' % r.text)
    quit(1)

Clarify error if otp is wrong

Clarify error if otp is wrong

Response:
<REPLACE_OLD> %s' <REPLACE_NEW> %s. Is the OTP correct? Double-check on Spire!' <REPLACE_END> <|endoftext|> #!/usr/bin/python
"""An example demonstrating the client-side usage
of the cretificate request API endpoint.
"""

import requests, sys, json

otp = sys.argv[1]

domain_req_url = 'https://spire.cloudfleet.io/api/v1/blimp/domain'
domain_txt_path = '/opt/cloudfleet/data/config/domain.txt'

print('retrieving domain for blimp: ' + domain_req_url)

r = requests.get(domain_req_url, headers={'X-AUTH-OTP': otp})

if r.status_code == 200:
    print('Success: %s' % r.text)
    result_dict = r.json()

    if "domain" in result_dict:
        with open(domain_txt_path, 'w') as domain_txt_file:
            domain_txt_file.write(result_dict['domain'])
        quit(0)
    else:
        quit(1)
else:
    print('Error: %s. Is the OTP correct? Double-check on Spire!' % r.text)
    quit(1)

Prompt:
Clarify error if otp is wrong
#!/usr/bin/python
"""An example demonstrating the client-side usage
of the cretificate request API endpoint.
"""

import requests, sys, json

otp = sys.argv[1]

domain_req_url = 'https://spire.cloudfleet.io/api/v1/blimp/domain'
domain_txt_path = '/opt/cloudfleet/data/config/domain.txt'

print('retrieving domain for blimp: ' + domain_req_url)

r = requests.get(domain_req_url, headers={'X-AUTH-OTP': otp})

if r.status_code == 200:
    print('Success: %s' % r.text)
    result_dict = r.json()

    if "domain" in result_dict:
        with open(domain_txt_path, 'w') as domain_txt_file:
            domain_txt_file.write(result_dict['domain'])
        quit(0)
    else:
        quit(1)
else:
    print('Error: %s' % r.text)
    quit(1)


import psycopg2
import os
import getpass

# CREATE DATABASE bedquilt_test
#   WITH OWNER = {{owner}}
#        ENCODING = 'UTF8'
#        TABLESPACE = pg_default
#        LC_COLLATE = 'en_GB.UTF-8'
#        LC_CTYPE = 'en_GB.UTF-8'
#        CONNECTION LIMIT = -1;

def get_pg_connection():
    return psycopg2.connect(
        "dbname=bedquilt_test user={}".format(getpass.getuser())
    )

Add the sql to create the test database

Add the sql to create the test database

Response:
<REPLACE_OLD> getpass

def <REPLACE_NEW> getpass

# CREATE DATABASE bedquilt_test
#   WITH OWNER = {{owner}}
#        ENCODING = 'UTF8'
#        TABLESPACE = pg_default
#        LC_COLLATE = 'en_GB.UTF-8'
#        LC_CTYPE = 'en_GB.UTF-8'
#        CONNECTION LIMIT = -1;

def <REPLACE_END> <|endoftext|> import psycopg2
import os
import getpass

# CREATE DATABASE bedquilt_test
#   WITH OWNER = {{owner}}
#        ENCODING = 'UTF8'
#        TABLESPACE = pg_default
#        LC_COLLATE = 'en_GB.UTF-8'
#        LC_CTYPE = 'en_GB.UTF-8'
#        CONNECTION LIMIT = -1;

def get_pg_connection():
    return psycopg2.connect(
        "dbname=bedquilt_test user={}".format(getpass.getuser())
    )

Prompt:
Add the sql to create the test database

import psycopg2
import os
import getpass

def get_pg_connection():
    return psycopg2.connect(
        "dbname=bedquilt_test user={}".format(getpass.getuser())
    )


# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim

def render(item, **fields):
    """ Render the given item
    """
    if item is None:
        return ''
    elif isinstance(item, Renderer):
        return item.render(**fields)
    elif isinstance(item, list):
        return ''.join(render(e) for e in item)
    else:
        return str(item)

class Renderer(object):
    template = ''
    _counter = itertools.count()

    def __init__(self, template=None):
        if template is not None:
            self.template = template

    def counter(self):
        return next(self._counter)

    def render_fields(self, fields):
        pass

    def render(self, template=None, **kwargs):
        fields = ({k:v for k, v in vars(self).items() if not k.startswith('_')})

        override = self.render_fields(fields)
        if template is None:
            if override is not None:
                template = override
            else:
                template = self.template

        fields.update(kwargs)
        fields = {k:render(v) for k, v in fields.items()}
        try:
            return trim(template).format(**fields)
        except KeyError as e:
            raise KeyError(str(e), type(self))

Response:
<REPLACE_OLD> **fields):
        fields.update({k:v <REPLACE_NEW> **kwargs):
        fields = ({k:v <REPLACE_END> <REPLACE_OLD> k.startswith('_')})
        <REPLACE_NEW> k.startswith('_')})

        override = <REPLACE_END> <REPLACE_OLD> template = self.template
 <REPLACE_NEW> if override is not None:
                template = override
            else:
                template = self.template

        fields.update(kwargs)
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim

def render(item, **fields):
    """ Render the given item
    """
    if item is None:
        return ''
    elif isinstance(item, Renderer):
        return item.render(**fields)
    elif isinstance(item, list):
        return ''.join(render(e) for e in item)
    else:
        return str(item)

class Renderer(object):
    template = ''
    _counter = itertools.count()

    def __init__(self, template=None):
        if template is not None:
            self.template = template

    def counter(self):
        return next(self._counter)

    def render_fields(self, fields):
        pass

    def render(self, template=None, **kwargs):
        fields = ({k:v for k, v in vars(self).items() if not k.startswith('_')})

        override = self.render_fields(fields)
        if template is None:
            if override is not None:
                template = override
            else:
                template = self.template

        fields.update(kwargs)
        fields = {k:render(v) for k, v in fields.items()}
        try:
            return trim(template).format(**fields)
        except KeyError as e:
            raise KeyError(str(e), type(self))

Prompt:
Allow override of template through return value of render_fields.

# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim

def render(item, **fields):
    """ Render the given item
    """
    if item is None:
        return ''
    elif isinstance(item, Renderer):
        return item.render(**fields)
    elif isinstance(item, list):
        return ''.join(render(e) for e in item)
    else:
        return str(item)

class Renderer(object):
    template = ''
    _counter = itertools.count()

    def __init__(self, template=None):
        if template is not None:
            self.template = template

    def counter(self):
        return next(self._counter)

    def render_fields(self, fields):
        pass

    def render(self, template=None, **fields):
        fields.update({k:v for k, v in vars(self).items() if not k.startswith('_')})
        self.render_fields(fields)
        if template is None:
            template = self.template
        fields = {k:render(v) for k, v in fields.items()}
        try:
            return trim(template).format(**fields)
        except KeyError as e:
            raise KeyError(str(e), type(self))


"""API errors."""
from werkzeug.exceptions import HTTPException

class Error(Exception):
    status = 500
    error = "internal server error"

    def __init__(self, error=None, status=None):
        """Create an API error with the given error and status code."""
        self.status = status or self.__class__.status
        self.error = error or self.__class__.error

    @property
    def response(self):
        """Return the error as a repsonse tuple."""
        return {'error': self.error}, self.status

def get_error_response(error):
    """Return an error as a response tuple."""
    if isinstance(error, HTTPException):
        error = Error(error.name, error.code)
    if not isinstance(error, Error):
        error = Error()
    return error.response

Response:
<REPLACE_OLD> {'status': self.status, 'error': <REPLACE_NEW> {'error': <REPLACE_END> <|endoftext|> """API errors."""
from werkzeug.exceptions import HTTPException

class Error(Exception):
    status = 500
    error = "internal server error"

    def __init__(self, error=None, status=None):
        """Create an API error with the given error and status code."""
        self.status = status or self.__class__.status
        self.error = error or self.__class__.error

    @property
    def response(self):
        """Return the error as a repsonse tuple."""
        return {'error': self.error}, self.status

def get_error_response(error):
    """Return an error as a response tuple."""
    if isinstance(error, HTTPException):
        error = Error(error.name, error.code)
    if not isinstance(error, Error):
        error = Error()
    return error.response

Prompt:
Remove redundant status code from error response body.

"""API errors."""
from werkzeug.exceptions import HTTPException

class Error(Exception):
    status = 500
    error = "internal server error"

    def __init__(self, error=None, status=None):
        """Create an API error with the given error and status code."""
        self.status = status or self.__class__.status
        self.error = error or self.__class__.error

    @property
    def response(self):
        """Return the error as a repsonse tuple."""
        return {'status': self.status, 'error': self.error}, self.status

def get_error_response(error):
    """Return an error as a response tuple."""
    if isinstance(error, HTTPException):
        error = Error(error.name, error.code)
    if not isinstance(error, Error):
        error = Error()
    return error.response


# coding: utf-8

# A jinja extension for the harness

# In[9]:

try:
    from .base import HarnessExtension
except:
    from base import HarnessExtension

import pandas, sklearn.model_selection as model_selection
from toolz.curried import first

# In[10]:

class SciKitExtension(HarnessExtension):
    alias = 'sklearn'
    def keywords(self, dataframe):
        return {
            'X': lambda: dataframe.values,
            'y': lambda:
            dataframe.index.get_level_values(dataframe.feature_level)
            if dataframe.feature_level else None,
        }

    def pipe(self, dataframe, attr):
        self.module_ = dataframe.estimator
        return super().pipe(dataframe, attr)

    def callback(self, dataframe, value):
        if value is dataframe.estimator:
            return dataframe
        if isinstance(value, pandas.np.ndarray):
            return dataframe.__class__(
                value,
                index=dataframe.index,
                feature_level=dataframe.feature_level,
            )
        if isinstance(value, pandas.CategoricalIndex):
            # new dataframe
            value = dataframe.set_index(value, append=True)

            value.index = value.index.reorder_levels([-1, *range(
                        len(dataframe.index.levels) if hasattr(dataframe.index, 'levels') else 1
                    )])

        return value

Response:
<DELETE> In[11]:

get_ipython().magic('pinfo2 model_selection.ShuffleSplit')

# <DELETE_END> <|endoftext|>
# coding: utf-8

# A jinja extension for the harness

# In[9]:

try:
    from .base import HarnessExtension
except:
    from base import HarnessExtension

import pandas, sklearn.model_selection as model_selection
from toolz.curried import first

# In[10]:

class SciKitExtension(HarnessExtension):
    alias = 'sklearn'
    def keywords(self, dataframe):
        return {
            'X': lambda: dataframe.values,
            'y': lambda:
            dataframe.index.get_level_values(dataframe.feature_level)
            if dataframe.feature_level else None,
        }

    def pipe(self, dataframe, attr):
        self.module_ = dataframe.estimator
        return super().pipe(dataframe, attr)

    def callback(self, dataframe, value):
        if value is dataframe.estimator:
            return dataframe
        if isinstance(value, pandas.np.ndarray):
            return dataframe.__class__(
                value,
                index=dataframe.index,
                feature_level=dataframe.feature_level,
            )
        if isinstance(value, pandas.CategoricalIndex):
            # new dataframe
            value = dataframe.set_index(value, append=True)

            value.index = value.index.reorder_levels([-1, *range(
                        len(dataframe.index.levels) if hasattr(dataframe.index, 'levels') else 1
                    )])

        return value

Prompt:
Fix error message in the scikitlearn extension.

# coding: utf-8

# A jinja extension for the harness

# In[9]:

try:
    from .base import HarnessExtension
except:
    from base import HarnessExtension

import pandas, sklearn.model_selection as model_selection
from toolz.curried import first

# In[11]:

get_ipython().magic('pinfo2 model_selection.ShuffleSplit')

# In[10]:

class SciKitExtension(HarnessExtension):
    alias = 'sklearn'
    def keywords(self, dataframe):
        return {
            'X': lambda: dataframe.values,
            'y': lambda:
            dataframe.index.get_level_values(dataframe.feature_level)
            if dataframe.feature_level else None,
        }

    def pipe(self, dataframe, attr):
        self.module_ = dataframe.estimator
        return super().pipe(dataframe, attr)

    def callback(self, dataframe, value):
        if value is dataframe.estimator:
            return dataframe
        if isinstance(value, pandas.np.ndarray):
            return dataframe.__class__(
                value,
                index=dataframe.index,
                feature_level=dataframe.feature_level,
            )
        if isinstance(value, pandas.CategoricalIndex):
            # new dataframe
            value = dataframe.set_index(value, append=True)

            value.index = value.index.reorder_levels([-1, *range(
                        len(dataframe.index.levels) if hasattr(dataframe.index, 'levels') else 1
                    )])

        return value


#! /usr/bin/env python
"""Echo server in socket connection: receives and sends back a message."""
import socket

def response_ok():
    """Return byte string 200 ok response."""
    return u"HTTP/1.1 200 OK\nContent-Type: text/plain\nContent-length: 18\n\r\neverything is okay".encode('utf-8')

def reponse_error(error_code, reason):
    """Return byte string error code."""
    return u"HTTP/1.1 {} {}".format(error_code, reason).encode('utf-8')

if __name__ == '__main__':
    """Run from terminal, this will recieve a messages and send them back."""
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
                                  socket.IPPROTO_IP)
    server_socket.bind(('127.0.0.1', 50000))
    server_socket.listen(1)
    buffsize = 32
    try:
        while True:
            msg = ''
            done = False
            conn, addr = server_socket.accept()
            while not done:
                msg_part = conn.recv(buffsize)
                msg += msg_part
                if len(msg_part) < buffsize:
                    done = True
                    conn.sendall(msg)
                    conn.shutdown(socket.SHUT_WR)
                    conn.close()
    except KeyboardInterrupt:
        print 'I successfully stopped.'
        server_socket.close()

Response:
<REPLACE_OLD> socket

if <REPLACE_NEW> socket

def response_ok():
    """Return byte string 200 ok response."""
    return u"HTTP/1.1 200 OK\nContent-Type: text/plain\nContent-length: 18\n\r\neverything is okay".encode('utf-8')

def reponse_error(error_code, reason):
    """Return byte string error code."""
    return u"HTTP/1.1 {} {}".format(error_code, reason).encode('utf-8')

if <REPLACE_END> <|endoftext|> #! /usr/bin/env python
"""Echo server in socket connection: receives and sends back a message."""
import socket

def response_ok():
    """Return byte string 200 ok response."""
    return u"HTTP/1.1 200 OK\nContent-Type: text/plain\nContent-length: 18\n\r\neverything is okay".encode('utf-8')

def reponse_error(error_code, reason):
    """Return byte string error code."""
    return u"HTTP/1.1 {} {}".format(error_code, reason).encode('utf-8')

if __name__ == '__main__':
    """Run from terminal, this will recieve a messages and send them back."""
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
                                  socket.IPPROTO_IP)
    server_socket.bind(('127.0.0.1', 50000))
    server_socket.listen(1)
    buffsize = 32
    try:
        while True:
            msg = ''
            done = False
            conn, addr = server_socket.accept()
            while not done:
                msg_part = conn.recv(buffsize)
                msg += msg_part
                if len(msg_part) < buffsize:
                    done = True
                    conn.sendall(msg)
                    conn.shutdown(socket.SHUT_WR)
                    conn.close()
    except KeyboardInterrupt:
        print 'I successfully stopped.'
        server_socket.close()

Prompt:
Add response_ok and response_error methods which return byte strings.

#! /usr/bin/env python
"""Echo server in socket connection: receives and sends back a message."""
import socket

if __name__ == '__main__':
    """Run from terminal, this will recieve a messages and send them back."""
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM,
                                  socket.IPPROTO_IP)
    server_socket.bind(('127.0.0.1', 50000))
    server_socket.listen(1)
    buffsize = 32
    try:
        while True:
            msg = ''
            done = False
            conn, addr = server_socket.accept()
            while not done:
                msg_part = conn.recv(buffsize)
                msg += msg_part
                if len(msg_part) < buffsize:
                    done = True
                    conn.sendall(msg)
                    conn.shutdown(socket.SHUT_WR)
                    conn.close()
    except KeyboardInterrupt:
        print 'I successfully stopped.'
        server_socket.close()


#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

from ai.h2o.sparkling.ExternalBackendConf import ExternalBackendConf
from ai.h2o.sparkling.Initializer import Initializer
from ai.h2o.sparkling.InternalBackendConf import InternalBackendConf
from ai.h2o.sparkling.SharedBackendConf import SharedBackendConf
from pyspark.ml.util import _jvm

class H2OConf(SharedBackendConf, InternalBackendConf, ExternalBackendConf):
    def __init__(self):
        try:
            Initializer.load_sparkling_jar()
            self._jconf = _jvm().org.apache.spark.h2o.H2OConf()
        except:
            raise

Response:
<REPLACE_OLD> License.
#

import warnings
from <REPLACE_NEW> License.
#

from <REPLACE_END> <REPLACE_OLD> __init__(self, spark=None):
 <REPLACE_NEW> __init__(self):
 <REPLACE_END> <DELETE>            if spark is not None:
                warnings.warn(
                    "Constructor H2OConf(spark) with spark argument is deprecated. Please use just H2OConf(). "
                    "The argument will be removed in release 3.32.")
 <DELETE_END> <|endoftext|> #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

from ai.h2o.sparkling.ExternalBackendConf import ExternalBackendConf
from ai.h2o.sparkling.Initializer import Initializer
from ai.h2o.sparkling.InternalBackendConf import InternalBackendConf
from ai.h2o.sparkling.SharedBackendConf import SharedBackendConf
from pyspark.ml.util import _jvm

class H2OConf(SharedBackendConf, InternalBackendConf, ExternalBackendConf):
    def __init__(self):
        try:
            Initializer.load_sparkling_jar()
            self._jconf = _jvm().org.apache.spark.h2o.H2OConf()
        except:
            raise

Prompt:
[SW-1971][FollowUp] Remove deprecated method H2OContext.getOrCreate with sparkSession or SparkContext argument

#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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 warnings
from ai.h2o.sparkling.ExternalBackendConf import ExternalBackendConf
from ai.h2o.sparkling.Initializer import Initializer
from ai.h2o.sparkling.InternalBackendConf import InternalBackendConf
from ai.h2o.sparkling.SharedBackendConf import SharedBackendConf
from pyspark.ml.util import _jvm

class H2OConf(SharedBackendConf, InternalBackendConf, ExternalBackendConf):
    def __init__(self, spark=None):
        try:
            if spark is not None:
                warnings.warn(
                    "Constructor H2OConf(spark) with spark argument is deprecated. Please use just H2OConf(). "
                    "The argument will be removed in release 3.32.")
            Initializer.load_sparkling_jar()
            self._jconf = _jvm().org.apache.spark.h2o.H2OConf()
        except:
            raise


import logging
from django.core.management.base import BaseCommand
from apps.processing.ala.util import util
from dateutil.parser import parse
from datetime import date, timedelta

logger = logging.getLogger(__name__)

class Command(BaseCommand):
    help = 'Import data from ALA stations, optionally you can pass date. Otherwise it will fetch yesterday data'

    def add_arguments(self, parser):
        parser.add_argument('date', nargs='?', type=parse, default=None)

    def handle(self, *args, **options):

        stations = util.get_or_create_stations()
        day = options['date']
        if day is None:
            day = date.today() - timedelta(2)

        logger.info(
            'Importing observations of {} ALA stations from {}.'.format(
                len(stations),
                day
            )
        )

        try:
            for station in stations:
                util.load(station, day)
                util.create_avgs(station, day)
        except Exception as e:
            self.stdout.write(self.style.ERROR(e))

Response:
<REPLACE_OLD> timedelta(1)

 <REPLACE_NEW> timedelta(2)

 <REPLACE_END> <|endoftext|> import logging
from django.core.management.base import BaseCommand
from apps.processing.ala.util import util
from dateutil.parser import parse
from datetime import date, timedelta

logger = logging.getLogger(__name__)

class Command(BaseCommand):
    help = 'Import data from ALA stations, optionally you can pass date. Otherwise it will fetch yesterday data'

    def add_arguments(self, parser):
        parser.add_argument('date', nargs='?', type=parse, default=None)

    def handle(self, *args, **options):

        stations = util.get_or_create_stations()
        day = options['date']
        if day is None:
            day = date.today() - timedelta(2)

        logger.info(
            'Importing observations of {} ALA stations from {}.'.format(
                len(stations),
                day
            )
        )

        try:
            for station in stations:
                util.load(station, day)
                util.create_avgs(station, day)
        except Exception as e:
            self.stdout.write(self.style.ERROR(e))

Prompt:
Make default ALA's date the day before yesterday

import logging
from django.core.management.base import BaseCommand
from apps.processing.ala.util import util
from dateutil.parser import parse
from datetime import date, timedelta

logger = logging.getLogger(__name__)

class Command(BaseCommand):
    help = 'Import data from ALA stations, optionally you can pass date. Otherwise it will fetch yesterday data'

    def add_arguments(self, parser):
        parser.add_argument('date', nargs='?', type=parse, default=None)

    def handle(self, *args, **options):

        stations = util.get_or_create_stations()
        day = options['date']
        if day is None:
            day = date.today() - timedelta(1)

        logger.info(
            'Importing observations of {} ALA stations from {}.'.format(
                len(stations),
                day
            )
        )

        try:
            for station in stations:
                util.load(station, day)
                util.create_avgs(station, day)
        except Exception as e:
            self.stdout.write(self.style.ERROR(e))


"""
The manager class for the CMS models
"""
from datetime import datetime
from django.db import models
from django.db.models.query import QuerySet
from django.db.models.query_utils import Q

class EntryQuerySet(QuerySet):
    def published(self):
        """
        Return only published entries
        """
        from fluent_blogs.models import Entry   # the import can't be globally, that gives a circular dependency
        return self \
            .filter(status=Entry.PUBLISHED) \
            .filter(
                Q(publication_date__isnull=True) |
                Q(publication_date__lte=datetime.now())
            ).filter(
                Q(publication_end_date__isnull=True) |
                Q(publication_end_date__gte=datetime.now())
            )

class EntryManager(models.Manager):
    """
    Extra methods attached to ``Entry.objects`` .
    """
    def get_query_set(self):
        return EntryQuerySet(self.model, using=self._db)

    def published(self):
        """
        Return only published entries
        """
        return self.get_query_set().published()

Response:
<REPLACE_OLD> Q(publication_date__lt=datetime.now())
 <REPLACE_NEW> Q(publication_date__lte=datetime.now())
 <REPLACE_END> <|endoftext|> """
The manager class for the CMS models
"""
from datetime import datetime
from django.db import models
from django.db.models.query import QuerySet
from django.db.models.query_utils import Q

class EntryQuerySet(QuerySet):
    def published(self):
        """
        Return only published entries
        """
        from fluent_blogs.models import Entry   # the import can't be globally, that gives a circular dependency
        return self \
            .filter(status=Entry.PUBLISHED) \
            .filter(
                Q(publication_date__isnull=True) |
                Q(publication_date__lte=datetime.now())
            ).filter(
                Q(publication_end_date__isnull=True) |
                Q(publication_end_date__gte=datetime.now())
            )

class EntryManager(models.Manager):
    """
    Extra methods attached to ``Entry.objects`` .
    """
    def get_query_set(self):
        return EntryQuerySet(self.model, using=self._db)

    def published(self):
        """
        Return only published entries
        """
        return self.get_query_set().published()

Prompt:
Fix .published() to accept current date as well.

"""
The manager class for the CMS models
"""
from datetime import datetime
from django.db import models
from django.db.models.query import QuerySet
from django.db.models.query_utils import Q

class EntryQuerySet(QuerySet):
    def published(self):
        """
        Return only published entries
        """
        from fluent_blogs.models import Entry   # the import can't be globally, that gives a circular dependency
        return self \
            .filter(status=Entry.PUBLISHED) \
            .filter(
                Q(publication_date__isnull=True) |
                Q(publication_date__lt=datetime.now())
            ).filter(
                Q(publication_end_date__isnull=True) |
                Q(publication_end_date__gte=datetime.now())
            )

class EntryManager(models.Manager):
    """
    Extra methods attached to ``Entry.objects`` .
    """
    def get_query_set(self):
        return EntryQuerySet(self.model, using=self._db)

    def published(self):
        """
        Return only published entries
        """
        return self.get_query_set().published()


from django_comments.forms import CommentForm

from django import forms
from django.utils.translation import ugettext_lazy as _
from bettertexts.models import TextComment

class TextCommentForm(CommentForm):

    def __init__(self, *args, **kwargs):
        super(TextCommentForm, self).__init__(*args, **kwargs)
        self.fields['name'].label = _("Name")
        self.fields['name'].required = True
        self.fields['email'].label = _("Email address")
        self.fields['email'].required = True
        self.fields['comment'].label = _('Comment')
        self.fields['comment'].required = True
        self.fields['url'].widget = forms.HiddenInput()

    inform = forms.BooleanField(required=False,
                                label=_('Keep me informed'),
                                widget=forms.CheckboxInput)

    involved = forms.BooleanField(required=False,
                                  label=_('Keep me involved'),
                                  widget=forms.CheckboxInput)

    class Meta:
        fields = ['name', 'email', 'inform', 'comment']

    def get_comment_model(self):
        """
        override to provide a custom comment model.
        """
        return TextComment

    def get_comment_create_data(self):
        """
        Override to add inform and involved field
        """
        data = super(TextCommentForm, self).get_comment_create_data()
        data.update({'inform': self.cleaned_data["inform"],
                     'involved': self.cleaned_data["involved"]})
        return data

Fix checkboxes inform and involved

Response:
<INSERT> and involved <INSERT_END> <REPLACE_OLD> True})
 <REPLACE_NEW> self.cleaned_data["inform"],
                     'involved': self.cleaned_data["involved"]})
 <REPLACE_END> <|endoftext|> from django_comments.forms import CommentForm

from django import forms
from django.utils.translation import ugettext_lazy as _
from bettertexts.models import TextComment

class TextCommentForm(CommentForm):

    def __init__(self, *args, **kwargs):
        super(TextCommentForm, self).__init__(*args, **kwargs)
        self.fields['name'].label = _("Name")
        self.fields['name'].required = True
        self.fields['email'].label = _("Email address")
        self.fields['email'].required = True
        self.fields['comment'].label = _('Comment')
        self.fields['comment'].required = True
        self.fields['url'].widget = forms.HiddenInput()

    inform = forms.BooleanField(required=False,
                                label=_('Keep me informed'),
                                widget=forms.CheckboxInput)

    involved = forms.BooleanField(required=False,
                                  label=_('Keep me involved'),
                                  widget=forms.CheckboxInput)

    class Meta:
        fields = ['name', 'email', 'inform', 'comment']

    def get_comment_model(self):
        """
        override to provide a custom comment model.
        """
        return TextComment

    def get_comment_create_data(self):
        """
        Override to add inform and involved field
        """
        data = super(TextCommentForm, self).get_comment_create_data()
        data.update({'inform': self.cleaned_data["inform"],
                     'involved': self.cleaned_data["involved"]})
        return data

Prompt:
CL011: Fix checkboxes inform and involved

from django_comments.forms import CommentForm

from django import forms
from django.utils.translation import ugettext_lazy as _
from bettertexts.models import TextComment

class TextCommentForm(CommentForm):

    def __init__(self, *args, **kwargs):
        super(TextCommentForm, self).__init__(*args, **kwargs)
        self.fields['name'].label = _("Name")
        self.fields['name'].required = True
        self.fields['email'].label = _("Email address")
        self.fields['email'].required = True
        self.fields['comment'].label = _('Comment')
        self.fields['comment'].required = True
        self.fields['url'].widget = forms.HiddenInput()

    inform = forms.BooleanField(required=False,
                                label=_('Keep me informed'),
                                widget=forms.CheckboxInput)

    involved = forms.BooleanField(required=False,
                                  label=_('Keep me involved'),
                                  widget=forms.CheckboxInput)

    class Meta:
        fields = ['name', 'email', 'inform', 'comment']

    def get_comment_model(self):
        """
        override to provide a custom comment model.
        """
        return TextComment

    def get_comment_create_data(self):
        """
        Override to add inform field
        """
        data = super(TextCommentForm, self).get_comment_create_data()
        data.update({'inform': True})
        return data


#!/usr/bin/env python

# tests require pytest-cov and pytest-xdist
import os
import signal
import sys
import pytest

try:
    from pcaspy import Driver, SimpleServer
    from multiprocessing import Process

    def to_subproc():

        prefix = 'BSTEST:'
        pvdb = {
            'VAL': {
                'prec': 3,
            },
        }

        class myDriver(Driver):
            def __init__(self):
                super(myDriver, self).__init__()

        if __name__ == '__main__':
            server = SimpleServer()
            server.createPV(prefix, pvdb)
            driver = myDriver()

            # process CA transactions
            while True:
                try:
                    server.process(0.1)
                except KeyboardInterrupt:
                    break

    p = Process(target=to_subproc)
except ImportError:
    p = None

def run():
    if p is not None:
        p.start()
    try:
        # adding rxs to show extra info on skips and xfails
        args = ['--cov bluesky -srx -vv']
        args.extend(sys.argv)
        pytest.main(args)
    finally:
        if p is not None:
            os.kill(p.pid, signal.SIGINT)
            p.join()

if __name__ == '__main__':
    run()

Response:
<REPLACE_OLD> sys
from bluesky.testing.noseclasses import KnownFailure
import <REPLACE_NEW> sys
import <REPLACE_END> <INSERT> # adding rxs to show extra info on skips and xfails
        <INSERT_END> <REPLACE_OLD> bluesky']
 <REPLACE_NEW> bluesky -srx -vv']
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

# tests require pytest-cov and pytest-xdist
import os
import signal
import sys
import pytest

try:
    from pcaspy import Driver, SimpleServer
    from multiprocessing import Process

    def to_subproc():

        prefix = 'BSTEST:'
        pvdb = {
            'VAL': {
                'prec': 3,
            },
        }

        class myDriver(Driver):
            def __init__(self):
                super(myDriver, self).__init__()

        if __name__ == '__main__':
            server = SimpleServer()
            server.createPV(prefix, pvdb)
            driver = myDriver()

            # process CA transactions
            while True:
                try:
                    server.process(0.1)
                except KeyboardInterrupt:
                    break

    p = Process(target=to_subproc)
except ImportError:
    p = None

def run():
    if p is not None:
        p.start()
    try:
        # adding rxs to show extra info on skips and xfails
        args = ['--cov bluesky -srx -vv']
        args.extend(sys.argv)
        pytest.main(args)
    finally:
        if p is not None:
            os.kill(p.pid, signal.SIGINT)
            p.join()

if __name__ == '__main__':
    run()

Prompt:
TST: Remove deleted subpackage. Add better args to pytest

#!/usr/bin/env python

# tests require pytest-cov and pytest-xdist
import os
import signal
import sys
from bluesky.testing.noseclasses import KnownFailure
import pytest

try:
    from pcaspy import Driver, SimpleServer
    from multiprocessing import Process

    def to_subproc():

        prefix = 'BSTEST:'
        pvdb = {
            'VAL': {
                'prec': 3,
            },
        }

        class myDriver(Driver):
            def __init__(self):
                super(myDriver, self).__init__()

        if __name__ == '__main__':
            server = SimpleServer()
            server.createPV(prefix, pvdb)
            driver = myDriver()

            # process CA transactions
            while True:
                try:
                    server.process(0.1)
                except KeyboardInterrupt:
                    break

    p = Process(target=to_subproc)
except ImportError:
    p = None

def run():
    if p is not None:
        p.start()
    try:
        args = ['--cov bluesky']
        args.extend(sys.argv)
        pytest.main(args)
    finally:
        if p is not None:
            os.kill(p.pid, signal.SIGINT)
            p.join()

if __name__ == '__main__':
    run()


from __future__ import absolute_import

from django.core.urlresolvers import reverse

from sentry.plugins import plugins
from sentry.web.frontend.base import ProjectView

class ProjectPluginEnableView(ProjectView):
    required_scope = 'project:write'

    def post(self, request, organization, team, project, slug):
        try:
            plugin = plugins.get(slug)
        except KeyError:
            return self.redirect(reverse('sentry-configure-project-plugin', args=[project.organization.slug, project.slug, slug]))

        if plugin.is_enabled(project):
            return self.redirect(reverse('sentry-configure-project-plugin', args=[project.organization.slug, project.slug, slug]))

        plugin.enable(project=project)

        return self.redirect(reverse('sentry-configure-project-plugin', args=[project.organization.slug, project.slug, slug]))

Fix enable action on plugins

Fix enable action on plugins

Response:
<DELETE> not <DELETE_END> <|endoftext|> from __future__ import absolute_import

from django.core.urlresolvers import reverse

from sentry.plugins import plugins
from sentry.web.frontend.base import ProjectView

class ProjectPluginEnableView(ProjectView):
    required_scope = 'project:write'

    def post(self, request, organization, team, project, slug):
        try:
            plugin = plugins.get(slug)
        except KeyError:
            return self.redirect(reverse('sentry-configure-project-plugin', args=[project.organization.slug, project.slug, slug]))

        if plugin.is_enabled(project):
            return self.redirect(reverse('sentry-configure-project-plugin', args=[project.organization.slug, project.slug, slug]))

        plugin.enable(project=project)

        return self.redirect(reverse('sentry-configure-project-plugin', args=[project.organization.slug, project.slug, slug]))

Prompt:
Fix enable action on plugins

from __future__ import absolute_import

from django.core.urlresolvers import reverse

from sentry.plugins import plugins
from sentry.web.frontend.base import ProjectView

class ProjectPluginEnableView(ProjectView):
    required_scope = 'project:write'

    def post(self, request, organization, team, project, slug):
        try:
            plugin = plugins.get(slug)
        except KeyError:
            return self.redirect(reverse('sentry-configure-project-plugin', args=[project.organization.slug, project.slug, slug]))

        if not plugin.is_enabled(project):
            return self.redirect(reverse('sentry-configure-project-plugin', args=[project.organization.slug, project.slug, slug]))

        plugin.enable(project=project)

        return self.redirect(reverse('sentry-configure-project-plugin', args=[project.organization.slug, project.slug, slug]))


"""
Stuff for building namespace
"""

from _compat import *

class Namespace(object):
    """
    Backport of SimpleNamespace() class added in Python 3.3
    """
    __slots__ = '__doc__', '__dict__', '__weakref__'

    def __init__(self, **kwargs):
        super(Namespace, self).__init__()
        self.__dict__.update(kwargs)

    def __iter__(self):
        return iter(self.__dict__)
    def __getitem__(self, key):
        return self.__dict__[key]
    def __setitem__(self, key, value):
        self.__dict__[key] = value
    def __delitem__(self, key):
        del self.__dict__[key]

    __hash__ = None
    def __eq__(self, other):
        return self.__dict__ == other.__dict__

    def __repr__(self):
        keys = sorted(self.__dict__)
        items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
        return "{}({})".format(type(self).__name__, ", ".join(items))

Response:
<INSERT>        super(Namespace, self).__init__()
 <INSERT_END> <|endoftext|> """
Stuff for building namespace
"""

from _compat import *

class Namespace(object):
    """
    Backport of SimpleNamespace() class added in Python 3.3
    """
    __slots__ = '__doc__', '__dict__', '__weakref__'

    def __init__(self, **kwargs):
        super(Namespace, self).__init__()
        self.__dict__.update(kwargs)

    def __iter__(self):
        return iter(self.__dict__)
    def __getitem__(self, key):
        return self.__dict__[key]
    def __setitem__(self, key, value):
        self.__dict__[key] = value
    def __delitem__(self, key):
        del self.__dict__[key]

    __hash__ = None
    def __eq__(self, other):
        return self.__dict__ == other.__dict__

    def __repr__(self):
        keys = sorted(self.__dict__)
        items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
        return "{}({})".format(type(self).__name__, ", ".join(items))

Prompt:
util: Call super __init__ from Namespace.__init__

"""
Stuff for building namespace
"""

from _compat import *

class Namespace(object):
    """
    Backport of SimpleNamespace() class added in Python 3.3
    """
    __slots__ = '__doc__', '__dict__', '__weakref__'

    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

    def __iter__(self):
        return iter(self.__dict__)
    def __getitem__(self, key):
        return self.__dict__[key]
    def __setitem__(self, key, value):
        self.__dict__[key] = value
    def __delitem__(self, key):
        del self.__dict__[key]

    __hash__ = None
    def __eq__(self, other):
        return self.__dict__ == other.__dict__

    def __repr__(self):
        keys = sorted(self.__dict__)
        items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
        return "{}({})".format(type(self).__name__, ", ".join(items))


Add some more function tests.

Add some more function tests.

Response:
<INSERT> )

def test_no_args():
    assert_eval(
        '(def @a (+ 0 5))'
        '(@a)',
        1,
        5,
    )

def test_nested_calls():
    assert_eval(
        '(def @a $a (+ $a $b))'
        '(def @b (+ (@a 1 2) (@a 3 4)))'
        '(@b)',
        1,
        1,
        1 + 2 + 3 + 4,
    <INSERT_END> <|endoftext|> from .utils import assert_eval

def test_simple_func():
    assert_eval('(def @a $a 8) (@a)', 1, 8)

def test_simple_func_args():
    assert_eval(
        '(def @a $a $a)'
        '(@a 1)'
        '(@a 2)'
        '(@a 5)',
        1,
        1,
        2,
        5)

def test_func_args_overwrite_globals():
    assert_eval(
        '(def @a $a 3)'
        '(set $a 10)'
        '$a'
        '(@a 8)'
        '$a',
        1,
        10,
        10,
        3,
        8,
        )

def test_func_args_with_offset():
    assert_eval(
        '(def @a $d (+ $d $i))'
        '(def @b $i (+ $i $j))'
        '(@a 1 2 3)'
        '(@b 8 9 10)'
        '$a\n$b\n$c\n$d\n$e\n$i\n$j\n$k\n',
        1, 1,
        4,
        17,
        0, 0, 0, 1, 2, 8, 9, 10,
        )

def test_no_args():
    assert_eval(
        '(def @a (+ 0 5))'
        '(@a)',
        1,
        5,
    )

def test_nested_calls():
    assert_eval(
        '(def @a $a (+ $a $b))'
        '(def @b (+ (@a 1 2) (@a 3 4)))'
        '(@b)',
        1,
        1,
        1 + 2 + 3 + 4,
    )

Prompt:
Add some more function tests.

from .utils import assert_eval

def test_simple_func():
    assert_eval('(def @a $a 8) (@a)', 1, 8)

def test_simple_func_args():
    assert_eval(
        '(def @a $a $a)'
        '(@a 1)'
        '(@a 2)'
        '(@a 5)',
        1,
        1,
        2,
        5)

def test_func_args_overwrite_globals():
    assert_eval(
        '(def @a $a 3)'
        '(set $a 10)'
        '$a'
        '(@a 8)'
        '$a',
        1,
        10,
        10,
        3,
        8,
        )

def test_func_args_with_offset():
    assert_eval(
        '(def @a $d (+ $d $i))'
        '(def @b $i (+ $i $j))'
        '(@a 1 2 3)'
        '(@b 8 9 10)'
        '$a\n$b\n$c\n$d\n$e\n$i\n$j\n$k\n',
        1, 1,
        4,
        17,
        0, 0, 0, 1, 2, 8, 9, 10,
        )


from scikits.samplerate import resample
from tempfile import mkstemp
from os import remove
import scikits.audiolab as audiolab
# if you want make the down sample rate using scipy.signal
#import scipy.signal
import urllib2
import sys

if len(sys.argv)<2 :
        print 'Usage: %s <audio file.wav>' %sys.argv[0]
        sys.exit(0)
File=sys.argv[1]

#making a file temp for manipulation
cd, FileNameTmp    = mkstemp('TmpSpeechFile.flac')

#Frame Rate used by api speech from google
fr=16000.

#using audiolab to read wav file
Signal, fs = audiolab.wavread(File)[:2]

#changing the original sample rate to 16000fs fast mode
Signal = resample(Signal, fr/float(fs), 'sinc_best')

#changing sample rate from audio file using scipy this is a bit slow
#Signal=scipy.signal.resample(Signal,int(round(len(Getsignal)*fr)/float(fs)),window=None)

# file Format type
fmt         = audiolab.Format('flac', 'pcm16')
nchannels   = 1

# making the file .flac
afile =  audiolab.Sndfile(FileNameTmp, 'w', fmt, nchannels, fr)

#writing in the file
afile.write_frames(Signal)

#Sending to google the file .flac
url = "https://www.google.com/speech-api/v1/recognize?xjerr=1&client=chromium&lang=pt-BR"
flac=open(FileNameTmp,"rb").read()
header = {'Content-Type' : 'audio/x-flac; rate=16000'}
req = urllib2.Request(url, flac, header)
data = urllib2.urlopen(req)
print data.read()
remove(FileNameTmp)

Add google speech to text sample

Add google speech to text sample

Response:
<INSERT> from scikits.samplerate import resample
from tempfile import mkstemp
from os import remove
import scikits.audiolab as audiolab
# if you want make the down sample rate using scipy.signal
#import scipy.signal
import urllib2
import sys

if len(sys.argv)<2 :
 <INSERT_END> <INSERT>       print 'Usage: %s <audio file.wav>' %sys.argv[0]
        sys.exit(0)
File=sys.argv[1]

#making a file temp for manipulation
cd, FileNameTmp    = mkstemp('TmpSpeechFile.flac')

#Frame Rate used by api speech from google
fr=16000.

#using audiolab to read wav file
Signal, fs = audiolab.wavread(File)[:2]

#changing the original sample rate to 16000fs fast mode
Signal = resample(Signal, fr/float(fs), 'sinc_best')

#changing sample rate from audio file using scipy this is a bit slow
#Signal=scipy.signal.resample(Signal,int(round(len(Getsignal)*fr)/float(fs)),window=None)

# file Format type
fmt         = audiolab.Format('flac', 'pcm16')
nchannels   = 1

# making the file .flac
afile =  audiolab.Sndfile(FileNameTmp, 'w', fmt, nchannels, fr)

#writing in the file
afile.write_frames(Signal)

#Sending to google the file .flac
url = "https://www.google.com/speech-api/v1/recognize?xjerr=1&client=chromium&lang=pt-BR"
flac=open(FileNameTmp,"rb").read()
header = {'Content-Type' : 'audio/x-flac; rate=16000'}
req = urllib2.Request(url, flac, header)
data = urllib2.urlopen(req)
print data.read()
remove(FileNameTmp)
 <INSERT_END> <|endoftext|> from scikits.samplerate import resample
from tempfile import mkstemp
from os import remove
import scikits.audiolab as audiolab
# if you want make the down sample rate using scipy.signal
#import scipy.signal
import urllib2
import sys

if len(sys.argv)<2 :
        print 'Usage: %s <audio file.wav>' %sys.argv[0]
        sys.exit(0)
File=sys.argv[1]

#making a file temp for manipulation
cd, FileNameTmp    = mkstemp('TmpSpeechFile.flac')

#Frame Rate used by api speech from google
fr=16000.

#using audiolab to read wav file
Signal, fs = audiolab.wavread(File)[:2]

#changing the original sample rate to 16000fs fast mode
Signal = resample(Signal, fr/float(fs), 'sinc_best')

#changing sample rate from audio file using scipy this is a bit slow
#Signal=scipy.signal.resample(Signal,int(round(len(Getsignal)*fr)/float(fs)),window=None)

# file Format type
fmt         = audiolab.Format('flac', 'pcm16')
nchannels   = 1

# making the file .flac
afile =  audiolab.Sndfile(FileNameTmp, 'w', fmt, nchannels, fr)

#writing in the file
afile.write_frames(Signal)

#Sending to google the file .flac
url = "https://www.google.com/speech-api/v1/recognize?xjerr=1&client=chromium&lang=pt-BR"
flac=open(FileNameTmp,"rb").read()
header = {'Content-Type' : 'audio/x-flac; rate=16000'}
req = urllib2.Request(url, flac, header)
data = urllib2.urlopen(req)
print data.read()
remove(FileNameTmp)

Prompt: Add google speech to text sample