"""
ExtensionItem -- Graphical representation of an association.
"""

# TODO: for Extension.postload(): in some cases where the association ends
# are connected to the same Class, the head_end property is connected to the
# tail end and visa versa.

from gaphor import UML
from gaphor.UML.modelfactory import stereotypes_str
from gaphor.diagram.presentation import LinePresentation
from gaphor.diagram.shapes import Box, EditableText, Text
from gaphor.diagram.support import represents

@represents(UML.Extension)
class ExtensionItem(LinePresentation):
    """
    ExtensionItem represents associations.
    An ExtensionItem has two ExtensionEnd items. Each ExtensionEnd item
    represents a Property (with Property.association == my association).
    """

    def __init__(self, id=None, model=None):
        super().__init__(id, model)

        self.shape_middle = Box(
            Text(
                text=lambda: stereotypes_str(self.subject),
                style={"min-width": 0, "min-height": 0},
            ),
            EditableText(text=lambda: self.subject and self.subject.name or ""),
        )

        self.watch("subject<NamedElement>.name")
        self.watch("subject.appliedStereotype.classifier.name")

    def draw_head(self, context):
        cr = context.cairo
        cr.move_to(0, 0)
        cr.line_to(15, -10)
        cr.line_to(15, 10)
        cr.line_to(0, 0)
        cr.set_source_rgb(0, 0, 0)
        cr.fill()
        cr.move_to(15, 0)

Response:
<REPLACE_OLD> gaphor.diagram.diagramline import NamedLine

class ExtensionItem(NamedLine):
 <REPLACE_NEW> gaphor.UML.modelfactory import stereotypes_str
from gaphor.diagram.presentation import LinePresentation
from gaphor.diagram.shapes import Box, EditableText, Text
from gaphor.diagram.support import represents

@represents(UML.Extension)
class ExtensionItem(LinePresentation):
 <REPLACE_END> <DELETE> __uml__ = UML.Extension

    <DELETE_END> <REPLACE_OLD> NamedLine.__init__(self, id, model)
        self.watch("subject<Extension>.ownedEnd")

 <REPLACE_NEW> super().__init__(id, model)

        self.shape_middle = Box(
            Text(
                text=lambda: stereotypes_str(self.subject),
                style={"min-width": 0, "min-height": 0},
            ),
            EditableText(text=lambda: self.subject and self.subject.name or ""),
        )

        self.watch("subject<NamedElement>.name")
        self.watch("subject.appliedStereotype.classifier.name")

 <REPLACE_END> <|endoftext|> """
ExtensionItem -- Graphical representation of an association.
"""

# TODO: for Extension.postload(): in some cases where the association ends
# are connected to the same Class, the head_end property is connected to the
# tail end and visa versa.

from gaphor import UML
from gaphor.UML.modelfactory import stereotypes_str
from gaphor.diagram.presentation import LinePresentation
from gaphor.diagram.shapes import Box, EditableText, Text
from gaphor.diagram.support import represents

@represents(UML.Extension)
class ExtensionItem(LinePresentation):
    """
    ExtensionItem represents associations.
    An ExtensionItem has two ExtensionEnd items. Each ExtensionEnd item
    represents a Property (with Property.association == my association).
    """

    def __init__(self, id=None, model=None):
        super().__init__(id, model)

        self.shape_middle = Box(
            Text(
                text=lambda: stereotypes_str(self.subject),
                style={"min-width": 0, "min-height": 0},
            ),
            EditableText(text=lambda: self.subject and self.subject.name or ""),
        )

        self.watch("subject<NamedElement>.name")
        self.watch("subject.appliedStereotype.classifier.name")

    def draw_head(self, context):
        cr = context.cairo
        cr.move_to(0, 0)
        cr.line_to(15, -10)
        cr.line_to(15, 10)
        cr.line_to(0, 0)
        cr.set_source_rgb(0, 0, 0)
        cr.fill()
        cr.move_to(15, 0)

Prompt:
Convert Extension item to new line style

"""
ExtensionItem -- Graphical representation of an association.
"""

# TODO: for Extension.postload(): in some cases where the association ends
# are connected to the same Class, the head_end property is connected to the
# tail end and visa versa.

from gaphor import UML
from gaphor.diagram.diagramline import NamedLine

class ExtensionItem(NamedLine):
    """
    ExtensionItem represents associations.
    An ExtensionItem has two ExtensionEnd items. Each ExtensionEnd item
    represents a Property (with Property.association == my association).
    """

    __uml__ = UML.Extension

    def __init__(self, id=None, model=None):
        NamedLine.__init__(self, id, model)
        self.watch("subject<Extension>.ownedEnd")

    def draw_head(self, context):
        cr = context.cairo
        cr.move_to(0, 0)
        cr.line_to(15, -10)
        cr.line_to(15, 10)
        cr.line_to(0, 0)
        cr.set_source_rgb(0, 0, 0)
        cr.fill()
        cr.move_to(15, 0)


"""Fetches the blogs configured on the website to local files.

The local files dumped to are 'BLOGNAME.incoming.yml' in the
assets/blogs directory.

Should be run as a regular cron-job.  Must be run from within the
website virtual environment.

---

Copyright (c) 2013, University Radio York.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

* Redistributions of source code must retain the above copyright notice,
  this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import pyramid
import feedparser
import pickle

import lass.common.config

if __name__ == '__main__':
    blog_config = lass.common.config.from_yaml('sitewide/blogs')

    for name, config in blog_config.items():
        asset = 'assets:blogs/{}.incoming'.format(name)
        full_path = pyramid.path.AssetResolver().resolve(asset).abspath()

        feed = feedparser.parse(config['feed'])

        with open(full_path, 'wb+') as stream:
            pickle.dump(feed, stream)

Move the Python end of blog-fetch to LASS.

Response:
<REPLACE_OLD>  <REPLACE_NEW> """Fetches the blogs configured on the website to local files.

The local files dumped to are 'BLOGNAME.incoming.yml' in the
assets/blogs directory.

Should be run as a regular cron-job.  Must be run from within the
website virtual environment.

---

Copyright (c) 2013, University Radio York.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

* Redistributions of source code must retain the above copyright notice,
  this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import pyramid
import feedparser
import pickle

import lass.common.config

if __name__ == '__main__':
    blog_config = lass.common.config.from_yaml('sitewide/blogs')

    for name, config in blog_config.items():
        asset = 'assets:blogs/{}.incoming'.format(name)
        full_path = pyramid.path.AssetResolver().resolve(asset).abspath()

        feed = feedparser.parse(config['feed'])

        with open(full_path, 'wb+') as stream:
            pickle.dump(feed, stream)
 <REPLACE_END> <|endoftext|> """Fetches the blogs configured on the website to local files.

The local files dumped to are 'BLOGNAME.incoming.yml' in the
assets/blogs directory.

Should be run as a regular cron-job.  Must be run from within the
website virtual environment.

---

Copyright (c) 2013, University Radio York.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

* Redistributions of source code must retain the above copyright notice,
  this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import pyramid
import feedparser
import pickle

import lass.common.config

if __name__ == '__main__':
    blog_config = lass.common.config.from_yaml('sitewide/blogs')

    for name, config in blog_config.items():
        asset = 'assets:blogs/{}.incoming'.format(name)
        full_path = pyramid.path.AssetResolver().resolve(asset).abspath()

        feed = feedparser.parse(config['feed'])

        with open(full_path, 'wb+') as stream:
            pickle.dump(feed, stream)

Prompt: Move the Python end of blog-fetch to LASS.


import IPython.core.displaypub as displaypub
import json
from pandas import DataFrame

class DataFrameEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, DataFrame):
            return obj.to_records()
        return json.JSONEncoder.default(self, obj)

def publish_display_data(data):
    try:
        displaypub.publish_display_data('pycandela', data)
    except TypeError:
        displaypub.publish_display_data(data)

def component(name, options):
    js = ("""
require(['candela'], function (candela) {
    var vis = new candela.components['%s'](element.get(0), %s);
    vis.render();
});
""" % (name, json.dumps(options, cls=DataFrameEncoder)))

    publish_display_data({'application/javascript': js})

def init():
    js = """
require.config({
    paths: {
        candela: 'http://kitware.github.io/candela/candela-0.2.0-81be44f6'
    }
});

var outputElement = element;
require(['candela'], function (candela) {
    if (candela) {
        outputElement.append('
Candela loaded successfully.
');
    } else {
        outputElement.append('
Error loading Candela.
');
    }
});
"""

    publish_display_data({'application/javascript': js})

Fix import and call render() on vis

Fix import and call render() on vis

Response:
<REPLACE_OLD> json
import DataFrame from pandas

class <REPLACE_NEW> json
from pandas import DataFrame

class <REPLACE_END> <INSERT> var vis = <INSERT_END> <REPLACE_OLD> %s)
});
""" <REPLACE_NEW> %s);
    vis.render();
});
""" <REPLACE_END> <|endoftext|> import IPython.core.displaypub as displaypub
import json
from pandas import DataFrame

class DataFrameEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, DataFrame):
            return obj.to_records()
        return json.JSONEncoder.default(self, obj)

def publish_display_data(data):
    try:
        displaypub.publish_display_data('pycandela', data)
    except TypeError:
        displaypub.publish_display_data(data)

def component(name, options):
    js = ("""
require(['candela'], function (candela) {
    var vis = new candela.components['%s'](element.get(0), %s);
    vis.render();
});
""" % (name, json.dumps(options, cls=DataFrameEncoder)))

    publish_display_data({'application/javascript': js})

def init():
    js = """
require.config({
    paths: {
        candela: 'http://kitware.github.io/candela/candela-0.2.0-81be44f6'
    }
});

var outputElement = element;
require(['candela'], function (candela) {
    if (candela) {
        outputElement.append('<div>Candela loaded successfully.</div>');
    } else {
        outputElement.append('<div>Error loading Candela.</div>');
    }
});
"""

    publish_display_data({'application/javascript': js})

Prompt:
Fix import and call render() on vis

import IPython.core.displaypub as displaypub
import json
import DataFrame from pandas

class DataFrameEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, DataFrame):
            return obj.to_records()
        return json.JSONEncoder.default(self, obj)

def publish_display_data(data):
    try:
        displaypub.publish_display_data('pycandela', data)
    except TypeError:
        displaypub.publish_display_data(data)

def component(name, options):
    js = ("""
require(['candela'], function (candela) {
    new candela.components['%s'](element.get(0), %s)
});
""" % (name, json.dumps(options, cls=DataFrameEncoder)))

    publish_display_data({'application/javascript': js})

def init():
    js = """
require.config({
    paths: {
        candela: 'http://kitware.github.io/candela/candela-0.2.0-81be44f6'
    }
});

var outputElement = element;
require(['candela'], function (candela) {
    if (candela) {
        outputElement.append('
Candela loaded successfully.
');
    } else {
        outputElement.append('
Error loading Candela.
');
    }
});
"""

    publish_display_data({'application/javascript': js})


'''Virtual datasets: The 'Eiger' use case

https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf
'''

import h5py
import numpy as np

files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5']
entry_key = 'data' # where the data is inside of the source files.
sh = h5py.File(files[0], 'r')[entry_key].shape # get the first ones shape.

layout = h5py.VirtualLayout(shape=(len(files) * sh[0], ) + sh[1:], dtype=np.float)
M_start = 0
for i, filename in enumerate(files):
    M_end = M_start + sh[0]
    vsource = h5py.VirtualSource(filename, entry_key, shape=sh)
    layout[M_start:M_end:1, :, :] = vsource
    M_start = M_end

with h5py.File("eiger_vds.h5", 'w', libver='latest') as f:
    f.create_virtual_dataset('data', layout, fillvalue=0)

Fix layout for Eiger example

Fix layout for Eiger example

Response:
<REPLACE_OLD> h5py.VirtualLayout(shape=(len(files),) <REPLACE_NEW> h5py.VirtualLayout(shape=(len(files) * sh[0], ) <REPLACE_END> <REPLACE_OLD> sh, <REPLACE_NEW> sh[1:], <REPLACE_END> <|endoftext|> '''Virtual datasets: The 'Eiger' use case

https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf
'''

import h5py
import numpy as np

files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5']
entry_key = 'data' # where the data is inside of the source files.
sh = h5py.File(files[0], 'r')[entry_key].shape # get the first ones shape.

layout = h5py.VirtualLayout(shape=(len(files) * sh[0], ) + sh[1:], dtype=np.float)
M_start = 0
for i, filename in enumerate(files):
    M_end = M_start + sh[0]
    vsource = h5py.VirtualSource(filename, entry_key, shape=sh)
    layout[M_start:M_end:1, :, :] = vsource
    M_start = M_end

with h5py.File("eiger_vds.h5", 'w', libver='latest') as f:
    f.create_virtual_dataset('data', layout, fillvalue=0)

Prompt:
Fix layout for Eiger example

'''Virtual datasets: The 'Eiger' use case

https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf
'''

import h5py
import numpy as np

files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5']
entry_key = 'data' # where the data is inside of the source files.
sh = h5py.File(files[0], 'r')[entry_key].shape # get the first ones shape.

layout = h5py.VirtualLayout(shape=(len(files),) + sh, dtype=np.float)
M_start = 0
for i, filename in enumerate(files):
    M_end = M_start + sh[0]
    vsource = h5py.VirtualSource(filename, entry_key, shape=sh)
    layout[M_start:M_end:1, :, :] = vsource
    M_start = M_end

with h5py.File("eiger_vds.h5", 'w', libver='latest') as f:
    f.create_virtual_dataset('data', layout, fillvalue=0)


from setuptools import setup, find_packages
import sys, os

version = '0.1'

setup(name='kotti_contactform',
      version=version,
      description="Simple contact form for Kotti sites",
      long_description="""\
This is an extension to Kotti that allows to add simple contact forms to your website.""",
      classifiers=[
        "Development Status :: 3 - Alpha",
        "Programming Language :: Python",
        "Framework :: Pylons",
        "Topic :: Internet :: WWW/HTTP",
        "Topic :: Internet :: WWW/HTTP :: Dynamic Content",
        "Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
        "License :: OSI Approved :: BSD License",
        ],
      keywords='kotti contact form',
      author='Christian Neumann',
      author_email='christian@datenkarussell.de',
      url='http://pypi.python.org/pypi/kotti_contactform',
      license='BSD License',
      packages=['kotti_contactform'],
      package_data={'kotti_contactform': ['templates/*.pt',
                                          'locale/*.*',
                                          'locale/*/LC_MESSAGES/*.*']},
      include_package_data=True,
      zip_safe=False,
      install_requires=[
        'Kotti',
        'pyramid_mailer',
        'Babel',
      ],
      entry_points="""
      # -*- Entry points: -*-
      """,
      message_extractors = { "kotti_contactform": [
        ("**.py",   "chameleon_python", None ),
        ("**.pt",   "chameleon_xml", None ),
        ]},
      )

Add translation files to package data

Add translation files to package data

Response:
<REPLACE_OLD> ['templates/*.pt']},
 <REPLACE_NEW> ['templates/*.pt',
                                          'locale/*.*',
                                          'locale/*/LC_MESSAGES/*.*']},
 <REPLACE_END> <|endoftext|> from setuptools import setup, find_packages
import sys, os

version = '0.1'

setup(name='kotti_contactform',
      version=version,
      description="Simple contact form for Kotti sites",
      long_description="""\
This is an extension to Kotti that allows to add simple contact forms to your website.""",
      classifiers=[
        "Development Status :: 3 - Alpha",
        "Programming Language :: Python",
        "Framework :: Pylons",
        "Topic :: Internet :: WWW/HTTP",
        "Topic :: Internet :: WWW/HTTP :: Dynamic Content",
        "Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
        "License :: OSI Approved :: BSD License",
        ],
      keywords='kotti contact form',
      author='Christian Neumann',
      author_email='christian@datenkarussell.de',
      url='http://pypi.python.org/pypi/kotti_contactform',
      license='BSD License',
      packages=['kotti_contactform'],
      package_data={'kotti_contactform': ['templates/*.pt',
                                          'locale/*.*',
                                          'locale/*/LC_MESSAGES/*.*']},
      include_package_data=True,
      zip_safe=False,
      install_requires=[
        'Kotti',
        'pyramid_mailer',
        'Babel',
      ],
      entry_points="""
      # -*- Entry points: -*-
      """,
      message_extractors = { "kotti_contactform": [
        ("**.py",   "chameleon_python", None ),
        ("**.pt",   "chameleon_xml", None ),
        ]},
      )

Prompt:
Add translation files to package data

from setuptools import setup, find_packages
import sys, os

version = '0.1'

setup(name='kotti_contactform',
      version=version,
      description="Simple contact form for Kotti sites",
      long_description="""\
This is an extension to Kotti that allows to add simple contact forms to your website.""",
      classifiers=[
        "Development Status :: 3 - Alpha",
        "Programming Language :: Python",
        "Framework :: Pylons",
        "Topic :: Internet :: WWW/HTTP",
        "Topic :: Internet :: WWW/HTTP :: Dynamic Content",
        "Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
        "License :: OSI Approved :: BSD License",
        ],
      keywords='kotti contact form',
      author='Christian Neumann',
      author_email='christian@datenkarussell.de',
      url='http://pypi.python.org/pypi/kotti_contactform',
      license='BSD License',
      packages=['kotti_contactform'],
      package_data={'kotti_contactform': ['templates/*.pt']},
      include_package_data=True,
      zip_safe=False,
      install_requires=[
        'Kotti',
        'pyramid_mailer',
        'Babel',
      ],
      entry_points="""
      # -*- Entry points: -*-
      """,
      message_extractors = { "kotti_contactform": [
        ("**.py",   "chameleon_python", None ),
        ("**.pt",   "chameleon_xml", None ),
        ]},
      )


"""
Contains the python specific FileManager.
"""
import ast
import re
from pyqode.core.managers import FileManager

class PyFileManager(FileManager):
    """
    Extends file manager to override detect_encoding. With python, we can
    detect encoding by reading the two first lines of a file and extracting its
    encoding tag.

    """
    def detect_encoding(self, path):
        """
        For the implementation of encoding definitions in Python, look at:
        - http://www.python.org/dev/peps/pep-0263/

        .. note:: code taken and adapted from
            ```jedi.common.source_to_unicode.detect_encoding```
        """
        with open(path, 'rb') as file:
            source = file.read()
            # take care of line encodings (not in jedi)
            source = source.replace(b'\r', b'')
            source_str = str(source).replace('\\n', '\n')

        byte_mark = ast.literal_eval(r"b'\xef\xbb\xbf'")
        if source.startswith(byte_mark):
            # UTF-8 byte-order mark
            return 'utf-8'

        first_two_lines = re.match(r'(?:[^\n]*\n){0,2}', source_str).group(0)
        possible_encoding = re.search(r"coding[=:]\s*([-\w.]+)",
                                      first_two_lines)
        if possible_encoding:
            return possible_encoding.group(1)

    def open(self, path, encoding=None, use_cached_encoding=True):
        if encoding is None:
            encoding = self.detect_encoding(path)
        super().open(path, encoding=encoding,
                     use_cached_encoding=use_cached_encoding)

Response:
<REPLACE_OLD> possible_encoding.group(1)
        else:
            return super().detect_encoding(path)
 <REPLACE_NEW> possible_encoding.group(1)

    def open(self, path, encoding=None, use_cached_encoding=True):
        if encoding is None:
            encoding = self.detect_encoding(path)
        super().open(path, encoding=encoding,
                     use_cached_encoding=use_cached_encoding)
 <REPLACE_END> <|endoftext|> """
Contains the python specific FileManager.
"""
import ast
import re
from pyqode.core.managers import FileManager

class PyFileManager(FileManager):
    """
    Extends file manager to override detect_encoding. With python, we can
    detect encoding by reading the two first lines of a file and extracting its
    encoding tag.

    """
    def detect_encoding(self, path):
        """
        For the implementation of encoding definitions in Python, look at:
        - http://www.python.org/dev/peps/pep-0263/

        .. note:: code taken and adapted from
            ```jedi.common.source_to_unicode.detect_encoding```
        """
        with open(path, 'rb') as file:
            source = file.read()
            # take care of line encodings (not in jedi)
            source = source.replace(b'\r', b'')
            source_str = str(source).replace('\\n', '\n')

        byte_mark = ast.literal_eval(r"b'\xef\xbb\xbf'")
        if source.startswith(byte_mark):
            # UTF-8 byte-order mark
            return 'utf-8'

        first_two_lines = re.match(r'(?:[^\n]*\n){0,2}', source_str).group(0)
        possible_encoding = re.search(r"coding[=:]\s*([-\w.]+)",
                                      first_two_lines)
        if possible_encoding:
            return possible_encoding.group(1)

    def open(self, path, encoding=None, use_cached_encoding=True):
        if encoding is None:
            encoding = self.detect_encoding(path)
        super().open(path, encoding=encoding,
                     use_cached_encoding=use_cached_encoding)

Prompt:
Fix encoding detection in python (shebang line was not parsed anymore)

"""
Contains the python specific FileManager.
"""
import ast
import re
from pyqode.core.managers import FileManager

class PyFileManager(FileManager):
    """
    Extends file manager to override detect_encoding. With python, we can
    detect encoding by reading the two first lines of a file and extracting its
    encoding tag.

    """
    def detect_encoding(self, path):
        """
        For the implementation of encoding definitions in Python, look at:
        - http://www.python.org/dev/peps/pep-0263/

        .. note:: code taken and adapted from
            ```jedi.common.source_to_unicode.detect_encoding```
        """
        with open(path, 'rb') as file:
            source = file.read()
            # take care of line encodings (not in jedi)
            source = source.replace(b'\r', b'')
            source_str = str(source).replace('\\n', '\n')

        byte_mark = ast.literal_eval(r"b'\xef\xbb\xbf'")
        if source.startswith(byte_mark):
            # UTF-8 byte-order mark
            return 'utf-8'

        first_two_lines = re.match(r'(?:[^\n]*\n){0,2}', source_str).group(0)
        possible_encoding = re.search(r"coding[=:]\s*([-\w.]+)",
                                      first_two_lines)
        if possible_encoding:
            return possible_encoding.group(1)
        else:
            return super().detect_encoding(path)


from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
from collections import OrderedDict
import importlib
import sys
import six

def watermark():
    """
    Give the version of each of the dependencies -- useful for bug reports.

    Returns
    -------
    result : dict
        mapping the name of each package to its version string or, if an
        optional dependency is not installed, None
    """
    packages = ['six', 'numpy', 'scipy', 'matplotlib', 'pandas', 'pims',
                'pyyaml', 'metadatastore', 'filestore',
                'channelarchiver', 'bubblegum']
    result = OrderedDict()
    for package_name in packages:
        try:
            package = importlib.import_module(package_name)
        except ImportError:
            result[package_name] = None
        else:
            try:
                version = package.__version__
            except AttributeError as err:
                version = "FAILED TO DETECT: {0}".format(err)
        result[package_name] = version

    # enaml provides its version differently
    try:
        import enaml
    except ImportError:
        result['enaml'] = None
    else:
        from enaml.version import version_info
        result['enaml'] = _make_version_string(version_info)

    # ...as does Python
    version_info = sys.version_info
    result['python'] = _make_version_string(version_info)
    return result

def _make_version_string(version_info):
    version_string = '.'.join(map(str, [version_info[0], version_info[1],
                                  version_info[2]]))
    return version_string

Response:
<INSERT> sys
import <INSERT_END> <INSERT> try:
                <INSERT_END> <REPLACE_OLD> package.__version__

 <REPLACE_NEW> package.__version__
            except AttributeError as err:
                version = "FAILED TO DETECT: {0}".format(err)
        result[package_name] = version

 <REPLACE_END> <|endoftext|> from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
from collections import OrderedDict
import importlib
import sys
import six

def watermark():
    """
    Give the version of each of the dependencies -- useful for bug reports.

    Returns
    -------
    result : dict
        mapping the name of each package to its version string or, if an
        optional dependency is not installed, None
    """
    packages = ['six', 'numpy', 'scipy', 'matplotlib', 'pandas', 'pims',
                'pyyaml', 'metadatastore', 'filestore',
                'channelarchiver', 'bubblegum']
    result = OrderedDict()
    for package_name in packages:
        try:
            package = importlib.import_module(package_name)
        except ImportError:
            result[package_name] = None
        else:
            try:
                version = package.__version__
            except AttributeError as err:
                version = "FAILED TO DETECT: {0}".format(err)
        result[package_name] = version

    # enaml provides its version differently
    try:
        import enaml
    except ImportError:
        result['enaml'] = None
    else:
        from enaml.version import version_info
        result['enaml'] = _make_version_string(version_info)

    # ...as does Python
    version_info = sys.version_info
    result['python'] = _make_version_string(version_info)
    return result

def _make_version_string(version_info):
    version_string = '.'.join(map(str, [version_info[0], version_info[1],
                                  version_info[2]]))
    return version_string

Prompt:
FIX: Make watermark robust if __version__ attribute is missing.

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
from collections import OrderedDict
import importlib
import six

def watermark():
    """
    Give the version of each of the dependencies -- useful for bug reports.

    Returns
    -------
    result : dict
        mapping the name of each package to its version string or, if an
        optional dependency is not installed, None
    """
    packages = ['six', 'numpy', 'scipy', 'matplotlib', 'pandas', 'pims',
                'pyyaml', 'metadatastore', 'filestore',
                'channelarchiver', 'bubblegum']
    result = OrderedDict()
    for package_name in packages:
        try:
            package = importlib.import_module(package_name)
        except ImportError:
            result[package_name] = None
        else:
            version = package.__version__

    # enaml provides its version differently
    try:
        import enaml
    except ImportError:
        result['enaml'] = None
    else:
        from enaml.version import version_info
        result['enaml'] = _make_version_string(version_info)

    # ...as does Python
    version_info = sys.version_info
    result['python'] = _make_version_string(version_info)
    return result

def _make_version_string(version_info):
    version_string = '.'.join(map(str, [version_info[0], version_info[1],
                                  version_info[2]]))
    return version_string


""" Basic models, such as user profile """
from django.db import models

class Language(models.Model):
    name = models.CharField(max_length=40, null=False)
    learn_url = models.URLField(null=True, blank=True)

    @staticmethod
    def all():
        return [l.name for l in Language.objects.all()]
    def __unicode__(self):
        return self.name

class Repo(models.Model):
    # Full name is required
    full_name = models.CharField(max_length=300, null=False)
    url = models.URLField(null=True)
    language = models.ForeignKey(Language, related_name='repos')
    description = models.CharField(max_length=500, null=True, blank=True)

    def save(self, *args, **kwargs):
        '''Override save method to set default url.'''
        BASE = 'https://github.com/'
        # Default url to base url + full_name
        if not self.url:
            self.url = BASE + self.full_name
        super(Repo, self).save(*args, **kwargs)

    def __unicode__(self):
        return "{full_name}: {language}".format(full_name=self.full_name,
                                                language=self.language.name)

Increase max length for repo names

Increase max length for repo names

Response:
<REPLACE_OLD> models.CharField(max_length=30, <REPLACE_NEW> models.CharField(max_length=300, <REPLACE_END> <REPLACE_OLD> models.CharField(max_length=300, <REPLACE_NEW> models.CharField(max_length=500, <REPLACE_END> <|endoftext|> """ Basic models, such as user profile """
from django.db import models

class Language(models.Model):
    name = models.CharField(max_length=40, null=False)
    learn_url = models.URLField(null=True, blank=True)

    @staticmethod
    def all():
        return [l.name for l in Language.objects.all()]
    def __unicode__(self):
        return self.name

class Repo(models.Model):
    # Full name is required
    full_name = models.CharField(max_length=300, null=False)
    url = models.URLField(null=True)
    language = models.ForeignKey(Language, related_name='repos')
    description = models.CharField(max_length=500, null=True, blank=True)

    def save(self, *args, **kwargs):
        '''Override save method to set default url.'''
        BASE = 'https://github.com/'
        # Default url to base url + full_name
        if not self.url:
            self.url = BASE + self.full_name
        super(Repo, self).save(*args, **kwargs)

    def __unicode__(self):
        return "{full_name}: {language}".format(full_name=self.full_name,
                                                language=self.language.name)

Prompt:
Increase max length for repo names

""" Basic models, such as user profile """
from django.db import models

class Language(models.Model):
    name = models.CharField(max_length=40, null=False)
    learn_url = models.URLField(null=True, blank=True)

    @staticmethod
    def all():
        return [l.name for l in Language.objects.all()]
    def __unicode__(self):
        return self.name

class Repo(models.Model):
    # Full name is required
    full_name = models.CharField(max_length=30, null=False)
    url = models.URLField(null=True)
    language = models.ForeignKey(Language, related_name='repos')
    description = models.CharField(max_length=300, null=True, blank=True)

    def save(self, *args, **kwargs):
        '''Override save method to set default url.'''
        BASE = 'https://github.com/'
        # Default url to base url + full_name
        if not self.url:
            self.url = BASE + self.full_name
        super(Repo, self).save(*args, **kwargs)

    def __unicode__(self):
        return "{full_name}: {language}".format(full_name=self.full_name,
                                                language=self.language.name)


import pytest

from django.test import TestCase

from apps.explorer.views.mixins import DataTableMixin, SubsetSelectionMixin

class DataTableMixinTestCase(TestCase):

    def test_get_omics_units_must_be_implemented(self):

        class DataTableWithNoGetOmicsUnits(DataTableMixin):
            pass

        with pytest.raises(NotImplementedError):
            fake_session = dict()

            obj = DataTableWithNoGetOmicsUnits()
            obj.get_omics_units(fake_session)

class SubsetSelectionMixinTestCase(TestCase):

    def test_get_omics_units_must_be_implemented(self):

        class SubsetSelectionWithNoGetOmicsUnits(SubsetSelectionMixin):
            pass

        with pytest.raises(NotImplementedError):
            fake_session = dict()

            obj = SubsetSelectionWithNoGetOmicsUnits()
            obj.get_omics_units(fake_session)

Add tests for explorer views mixins

Add tests for explorer views mixins

Response:
<INSERT> import pytest

from django.test import TestCase

from apps.explorer.views.mixins import DataTableMixin, SubsetSelectionMixin

class DataTableMixinTestCase(TestCase):

 <INSERT_END> <INSERT>   def test_get_omics_units_must_be_implemented(self):

        class DataTableWithNoGetOmicsUnits(DataTableMixin):
            pass

        with pytest.raises(NotImplementedError):
            fake_session = dict()

            obj = DataTableWithNoGetOmicsUnits()
            obj.get_omics_units(fake_session)

class SubsetSelectionMixinTestCase(TestCase):

    def test_get_omics_units_must_be_implemented(self):

        class SubsetSelectionWithNoGetOmicsUnits(SubsetSelectionMixin):
            pass

        with pytest.raises(NotImplementedError):
            fake_session = dict()

            obj = SubsetSelectionWithNoGetOmicsUnits()
            obj.get_omics_units(fake_session)
 <INSERT_END> <|endoftext|> import pytest

from django.test import TestCase

from apps.explorer.views.mixins import DataTableMixin, SubsetSelectionMixin

class DataTableMixinTestCase(TestCase):

    def test_get_omics_units_must_be_implemented(self):

        class DataTableWithNoGetOmicsUnits(DataTableMixin):
            pass

        with pytest.raises(NotImplementedError):
            fake_session = dict()

            obj = DataTableWithNoGetOmicsUnits()
            obj.get_omics_units(fake_session)

class SubsetSelectionMixinTestCase(TestCase):

    def test_get_omics_units_must_be_implemented(self):

        class SubsetSelectionWithNoGetOmicsUnits(SubsetSelectionMixin):
            pass

        with pytest.raises(NotImplementedError):
            fake_session = dict()

            obj = SubsetSelectionWithNoGetOmicsUnits()
            obj.get_omics_units(fake_session)

Prompt: Add tests for explorer views mixins


from os import getenv
from webapp import create_app
from argparse import ArgumentParser

app = create_app(getenv('FLASK_CONFIG') or 'development')

def main():
    parser = ArgumentParser()
    parser.add_argument("-p", "--port", help="port number")
    args = parser.parse_args()
    port = int(args.port or 5000)
    app.run(port=port)

if __name__ == "__main__":
    main()

Fix in port number initialisation

Fix in port number initialisation

Response:
<REPLACE_OLD> None)
 <REPLACE_NEW> 5000)
 <REPLACE_END> <|endoftext|>
from os import getenv
from webapp import create_app
from argparse import ArgumentParser

app = create_app(getenv('FLASK_CONFIG') or 'development')

def main():
    parser = ArgumentParser()
    parser.add_argument("-p", "--port", help="port number")
    args = parser.parse_args()
    port = int(args.port or 5000)
    app.run(port=port)

if __name__ == "__main__":
    main()

Prompt:
Fix in port number initialisation

from os import getenv
from webapp import create_app
from argparse import ArgumentParser

app = create_app(getenv('FLASK_CONFIG') or 'development')

def main():
    parser = ArgumentParser()
    parser.add_argument("-p", "--port", help="port number")
    args = parser.parse_args()
    port = int(args.port or None)
    app.run(port=port)

if __name__ == "__main__":
    main()


"""
  Copyright 2014 Google Inc. All rights reserved.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
"""

# import logging
from os import path
# import StringIO
# from time import sleep
# from time import time
# import zipfile
# import webapp2
# from incremental_fonts_utils import prepare_bundle

tachyfont_major_version = 1
tachyfont_minor_version = 0

BASE_DIR = path.dirname(__file__)

def fontname_to_zipfile(fontname):
  family_dir = ''
  if fontname[0:10] == 'NotoSansJP':
    family_dir = 'NotoSansJP/'
  zip_path = BASE_DIR + '/fonts/' + family_dir + fontname + '.TachyFont.jar'
  return zip_path

Add a fontname to TachyFont Jar file mapper.

Response:
<INSERT> """
 <INSERT_END> <INSERT> Copyright 2014 Google Inc. All rights reserved.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
"""

# import logging
from os import path
# import StringIO
# from time import sleep
# from time import time
# import zipfile
# import webapp2
# from incremental_fonts_utils import prepare_bundle

tachyfont_major_version = 1
tachyfont_minor_version = 0

BASE_DIR = path.dirname(__file__)

def fontname_to_zipfile(fontname):
  family_dir = ''
  if fontname[0:10] == 'NotoSansJP':
    family_dir = 'NotoSansJP/'
  zip_path = BASE_DIR + '/fonts/' + family_dir + fontname + '.TachyFont.jar'
  return zip_path

 <INSERT_END> <|endoftext|> """
  Copyright 2014 Google Inc. All rights reserved.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
"""

# import logging
from os import path
# import StringIO
# from time import sleep
# from time import time
# import zipfile
# import webapp2
# from incremental_fonts_utils import prepare_bundle

tachyfont_major_version = 1
tachyfont_minor_version = 0

BASE_DIR = path.dirname(__file__)

def fontname_to_zipfile(fontname):
  family_dir = ''
  if fontname[0:10] == 'NotoSansJP':
    family_dir = 'NotoSansJP/'
  zip_path = BASE_DIR + '/fonts/' + family_dir + fontname + '.TachyFont.jar'
  return zip_path

Prompt: Add a fontname to TachyFont Jar file mapper.


#!/usr/bin/python3

import pykms
import time

card = pykms.Card()
res = pykms.ResourceManager(card)
conn = res.reserve_connector("")
crtc = res.reserve_crtc(conn)
mode = conn.get_default_mode()
modeb = mode.to_blob(card)
format = pykms.PixelFormat.ARGB8888
plane1 = res.reserve_generic_plane(crtc, format)
plane2 = res.reserve_generic_plane(crtc, format)

print("Got plane1 %d %d plane2 %d %d" %
      (plane1.idx, plane1.id, plane2.idx, plane2.id))

fb1 = pykms.DumbFramebuffer(card, mode.hdisplay, mode.vdisplay, format);
pykms.draw_test_pattern(fb1);

fb2 = pykms.DumbFramebuffer(card, mode.hdisplay >> 1, mode.vdisplay >> 1, format);
pykms.draw_test_pattern(fb2);

alpha = 0

req = pykms.AtomicReq(card)
req.add(conn, "CRTC_ID", crtc.id)
req.add(crtc, {"ACTIVE": 1,
	       "MODE_ID": modeb.id})
req.add_plane(plane1, fb1, crtc)
req.add_plane(plane2, fb2, crtc)

r = req.commit_sync(allow_modeset = True)
assert r == 0, "Initial commit failed: %d" % r

while alpha <= 0xFFFF:
	print("alpha %d" % (alpha >>  8))
	req = pykms.AtomicReq(card)
	req.add(plane2, {"alpha": alpha })
	r = req.commit_sync()
	assert r == 0, "alpha change commit failed: %d" % r
	alpha = alpha + 0xFF
	time.sleep(0.1)

input("press enter exit\n")

Add globa_alpha_test.py for DRM per plane "alpha" property testing

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

import pykms
import time

card = pykms.Card()
res = pykms.ResourceManager(card)
conn = res.reserve_connector("")
crtc = res.reserve_crtc(conn)
mode = conn.get_default_mode()
modeb = mode.to_blob(card)
format = pykms.PixelFormat.ARGB8888
plane1 = res.reserve_generic_plane(crtc, format)
plane2 = res.reserve_generic_plane(crtc, format)

print("Got plane1 %d %d plane2 %d %d" %
 <INSERT_END> <INSERT>     (plane1.idx, plane1.id, plane2.idx, plane2.id))

fb1 = pykms.DumbFramebuffer(card, mode.hdisplay, mode.vdisplay, format);
pykms.draw_test_pattern(fb1);

fb2 = pykms.DumbFramebuffer(card, mode.hdisplay >> 1, mode.vdisplay >> 1, format);
pykms.draw_test_pattern(fb2);

alpha = 0

req = pykms.AtomicReq(card)
req.add(conn, "CRTC_ID", crtc.id)
req.add(crtc, {"ACTIVE": 1,
	       "MODE_ID": modeb.id})
req.add_plane(plane1, fb1, crtc)
req.add_plane(plane2, fb2, crtc)

r = req.commit_sync(allow_modeset = True)
assert r == 0, "Initial commit failed: %d" % r

while alpha <= 0xFFFF:
	print("alpha %d" % (alpha >>  8))
	req = pykms.AtomicReq(card)
	req.add(plane2, {"alpha": alpha })
	r = req.commit_sync()
	assert r == 0, "alpha change commit failed: %d" % r
	alpha = alpha + 0xFF
	time.sleep(0.1)

input("press enter exit\n")
 <INSERT_END> <|endoftext|> #!/usr/bin/python3

import pykms
import time

card = pykms.Card()
res = pykms.ResourceManager(card)
conn = res.reserve_connector("")
crtc = res.reserve_crtc(conn)
mode = conn.get_default_mode()
modeb = mode.to_blob(card)
format = pykms.PixelFormat.ARGB8888
plane1 = res.reserve_generic_plane(crtc, format)
plane2 = res.reserve_generic_plane(crtc, format)

print("Got plane1 %d %d plane2 %d %d" %
      (plane1.idx, plane1.id, plane2.idx, plane2.id))

fb1 = pykms.DumbFramebuffer(card, mode.hdisplay, mode.vdisplay, format);
pykms.draw_test_pattern(fb1);

fb2 = pykms.DumbFramebuffer(card, mode.hdisplay >> 1, mode.vdisplay >> 1, format);
pykms.draw_test_pattern(fb2);

alpha = 0

req = pykms.AtomicReq(card)
req.add(conn, "CRTC_ID", crtc.id)
req.add(crtc, {"ACTIVE": 1,
	       "MODE_ID": modeb.id})
req.add_plane(plane1, fb1, crtc)
req.add_plane(plane2, fb2, crtc)

r = req.commit_sync(allow_modeset = True)
assert r == 0, "Initial commit failed: %d" % r

while alpha <= 0xFFFF:
	print("alpha %d" % (alpha >>  8))
	req = pykms.AtomicReq(card)
	req.add(plane2, {"alpha": alpha })
	r = req.commit_sync()
	assert r == 0, "alpha change commit failed: %d" % r
	alpha = alpha + 0xFF
	time.sleep(0.1)

input("press enter exit\n")

Prompt: Add globa_alpha_test.py for DRM per plane "alpha" property testing


#!/bin/env python
#
# Description:
#   Check if a glideinFactory is running
#
# Arguments:
#   $1 = glidein submit_dir (i.e. factory dir)
#
# Author:
#   Igor Sfiligoi Jul 9th 2008
#

import sys
import glideFactoryPidLib

try:
    startup_dir=sys.argv[1]
    factory_pid=glideFactoryPidLib.get_gfactory_pid(startup_dir)
except:
    print "Not running"
    sys.exit(1)

print "Running"
sys.exit(0)

Check if a glideinFactory is running

Check if a glideinFactory is running

Response:
<INSERT> #!/bin/env python
#
# Description:
# <INSERT_END> <INSERT>  Check if a glideinFactory is running
#
# Arguments:
#   $1 = glidein submit_dir (i.e. factory dir)
#
# Author:
#   Igor Sfiligoi Jul 9th 2008
#

import sys
import glideFactoryPidLib

try:
    startup_dir=sys.argv[1]
    factory_pid=glideFactoryPidLib.get_gfactory_pid(startup_dir)
except:
    print "Not running"
    sys.exit(1)

print "Running"
sys.exit(0)

 <INSERT_END> <|endoftext|> #!/bin/env python
#
# Description:
#   Check if a glideinFactory is running
#
# Arguments:
#   $1 = glidein submit_dir (i.e. factory dir)
#
# Author:
#   Igor Sfiligoi Jul 9th 2008
#

import sys
import glideFactoryPidLib

try:
    startup_dir=sys.argv[1]
    factory_pid=glideFactoryPidLib.get_gfactory_pid(startup_dir)
except:
    print "Not running"
    sys.exit(1)

print "Running"
sys.exit(0)

Prompt: Check if a glideinFactory is running


# -*- encoding: utf-8 -*-
from django.conf.urls import url, include
from django.views.decorators.csrf import csrf_exempt
from .views import CreateMenu,ListMenu,UpdateMenu,CreateSelection,ListSelection,CreateSubscriber

urlpatterns = [
    url(r'^menu/new$',CreateMenu.as_view(),name='Create Menu'),
    url(r'^menu/edit/(?P<pk>\d+)/$',UpdateMenu.as_view(),name='Update Menu'),
    url(r'^menu/list$',ListMenu.as_view(),name='List Menu'),
    url(r'^menu/selection$',ListSelection.as_view(),name='List Selection'),
    url(r'^menu/(?P<uuid>[0-9a-z-]+)$',CreateSelection.as_view(),name='Create Selection'),
    url(r'^subscriber/new$',CreateSubscriber.as_view(),name='Create Subscriber'),

]

Update Urls from nora_menu app

Update Urls from nora_menu app

Response:
<INSERT> # -*- encoding: utf-8 -*-
from django.conf.urls import url, include
from django.views.decorators.csrf import csrf_exempt
from .views import CreateMenu,ListMenu,UpdateMenu,CreateSelection,ListSelection,CreateSubscriber

urlpatterns = [
 <INSERT_END> <INSERT>   url(r'^menu/new$',CreateMenu.as_view(),name='Create Menu'),
    url(r'^menu/edit/(?P<pk>\d+)/$',UpdateMenu.as_view(),name='Update Menu'),
    url(r'^menu/list$',ListMenu.as_view(),name='List Menu'),
    url(r'^menu/selection$',ListSelection.as_view(),name='List Selection'),
    url(r'^menu/(?P<uuid>[0-9a-z-]+)$',CreateSelection.as_view(),name='Create Selection'),
    url(r'^subscriber/new$',CreateSubscriber.as_view(),name='Create Subscriber'),

] <INSERT_END> <|endoftext|> # -*- encoding: utf-8 -*-
from django.conf.urls import url, include
from django.views.decorators.csrf import csrf_exempt
from .views import CreateMenu,ListMenu,UpdateMenu,CreateSelection,ListSelection,CreateSubscriber

urlpatterns = [
    url(r'^menu/new$',CreateMenu.as_view(),name='Create Menu'),
    url(r'^menu/edit/(?P<pk>\d+)/$',UpdateMenu.as_view(),name='Update Menu'),
    url(r'^menu/list$',ListMenu.as_view(),name='List Menu'),
    url(r'^menu/selection$',ListSelection.as_view(),name='List Selection'),
    url(r'^menu/(?P<uuid>[0-9a-z-]+)$',CreateSelection.as_view(),name='Create Selection'),
    url(r'^subscriber/new$',CreateSubscriber.as_view(),name='Create Subscriber'),

]

Prompt: Update Urls from nora_menu app


import json
import functools
from flask import Flask, Response
from foxgami.red import Story

app = Flask(__name__)

@app.after_response
def add_content_headers(response):
    response.headers['Access-Control-Allow-Origin'] = '*'
    return response

def return_as_json(inner_f):
    @functools.wraps(inner_f)
    def new_f(*args, **kwargs):
        result = inner_f(*args, **kwargs)
        return Response(json.dumps(
            result,
            indent=4,
            separators=(', ', ': ')
            ), mimetype='application/json')
    return new_f

@app.route('/api/stories')
@return_as_json
def hardcoded_aww():
    return Story.find()

@app.route('/api/stories/<string:story_id>')
def get_story(story_id):
    return Story.get(story_id)

if __name__ == '__main__':
    app.run(debug=True)

Add Access-Control headers to python

Add Access-Control headers to python

Response:
<REPLACE_OLD> Flask(__name__)

def <REPLACE_NEW> Flask(__name__)

@app.after_response
def add_content_headers(response):
    response.headers['Access-Control-Allow-Origin'] = '*'
    return response

def <REPLACE_END> <|endoftext|> import json
import functools
from flask import Flask, Response
from foxgami.red import Story

app = Flask(__name__)

@app.after_response
def add_content_headers(response):
    response.headers['Access-Control-Allow-Origin'] = '*'
    return response

def return_as_json(inner_f):
    @functools.wraps(inner_f)
    def new_f(*args, **kwargs):
        result = inner_f(*args, **kwargs)
        return Response(json.dumps(
            result,
            indent=4,
            separators=(', ', ': ')
            ), mimetype='application/json')
    return new_f

@app.route('/api/stories')
@return_as_json
def hardcoded_aww():
    return Story.find()

@app.route('/api/stories/<string:story_id>')
def get_story(story_id):
    return Story.get(story_id)

if __name__ == '__main__':
    app.run(debug=True)

Prompt:
Add Access-Control headers to python

import json
import functools
from flask import Flask, Response
from foxgami.red import Story

app = Flask(__name__)

def return_as_json(inner_f):
    @functools.wraps(inner_f)
    def new_f(*args, **kwargs):
        result = inner_f(*args, **kwargs)
        return Response(json.dumps(
            result,
            indent=4,
            separators=(', ', ': ')
            ), mimetype='application/json')
    return new_f

@app.route('/api/stories')
@return_as_json
def hardcoded_aww():
    return Story.find()

@app.route('/api/stories/<string:story_id>')
def get_story(story_id):
    return Story.get(story_id)

if __name__ == '__main__':
    app.run(debug=True)


# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models

class ProjectConfiguration(models.TransientModel):
    _name = 'project.config.settings'
    _inherit = 'res.config.settings'

    company_id = fields.Many2one('res.company', string='Company', required=True,
        default=lambda self: self.env.user.company_id)
    module_pad = fields.Boolean("Collaborative Pads")
    module_hr_timesheet = fields.Boolean("Timesheets")
    module_project_timesheet_synchro = fields.Boolean("Awesome Timesheet")
    module_rating_project = fields.Boolean(string="Rating on Tasks")
    module_project_forecast = fields.Boolean(string="Forecasts")
    module_hr_holidays = fields.Boolean("Leave Management")
    module_hr_timesheet_attendance = fields.Boolean("Attendances")
    module_sale_timesheet = fields.Boolean("Time Billing")
    module_hr_expense = fields.Boolean("Expenses")
    group_subtask_project = fields.Boolean("Sub-tasks", implied_group="project.group_subtask_project")

    @api.onchange('module_sale_timesheet')
    def _onchange_module_sale_timesheet(self):
        if self.module_sale_timesheet:
            self.module_hr_timesheet = True

Response:
<REPLACE_OLD> implied_group="project.group_subtask_project")
 <REPLACE_NEW> implied_group="project.group_subtask_project")

    @api.onchange('module_sale_timesheet')
    def _onchange_module_sale_timesheet(self):
        if self.module_sale_timesheet:
            self.module_hr_timesheet = True
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models

class ProjectConfiguration(models.TransientModel):
    _name = 'project.config.settings'
    _inherit = 'res.config.settings'

    company_id = fields.Many2one('res.company', string='Company', required=True,
        default=lambda self: self.env.user.company_id)
    module_pad = fields.Boolean("Collaborative Pads")
    module_hr_timesheet = fields.Boolean("Timesheets")
    module_project_timesheet_synchro = fields.Boolean("Awesome Timesheet")
    module_rating_project = fields.Boolean(string="Rating on Tasks")
    module_project_forecast = fields.Boolean(string="Forecasts")
    module_hr_holidays = fields.Boolean("Leave Management")
    module_hr_timesheet_attendance = fields.Boolean("Attendances")
    module_sale_timesheet = fields.Boolean("Time Billing")
    module_hr_expense = fields.Boolean("Expenses")
    group_subtask_project = fields.Boolean("Sub-tasks", implied_group="project.group_subtask_project")

    @api.onchange('module_sale_timesheet')
    def _onchange_module_sale_timesheet(self):
        if self.module_sale_timesheet:
            self.module_hr_timesheet = True

Prompt:
[IMP] project: Enable `Timesheets` option if `Time Billing` is enabled

# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models

class ProjectConfiguration(models.TransientModel):
    _name = 'project.config.settings'
    _inherit = 'res.config.settings'

    company_id = fields.Many2one('res.company', string='Company', required=True,
        default=lambda self: self.env.user.company_id)
    module_pad = fields.Boolean("Collaborative Pads")
    module_hr_timesheet = fields.Boolean("Timesheets")
    module_project_timesheet_synchro = fields.Boolean("Awesome Timesheet")
    module_rating_project = fields.Boolean(string="Rating on Tasks")
    module_project_forecast = fields.Boolean(string="Forecasts")
    module_hr_holidays = fields.Boolean("Leave Management")
    module_hr_timesheet_attendance = fields.Boolean("Attendances")
    module_sale_timesheet = fields.Boolean("Time Billing")
    module_hr_expense = fields.Boolean("Expenses")
    group_subtask_project = fields.Boolean("Sub-tasks", implied_group="project.group_subtask_project")


import time
import curses
import curses.panel
import logging

class Base(object):
    def __init__(self, window):
        lines, columns = window.getmaxyx()
        self._window = curses.newwin(lines, columns)
        self._panel = curses.panel.new_panel(self._window)

    def writeStatusLine(self, measurements):
        line = 'time: {0}| {1} measurements, at most {2} visible'.format(time.asctime(), len(measurements), self.availableLines())
        columns = self.dimensions()['columns']
        self._window.addstr(0, 0, line.ljust(columns), curses.A_REVERSE)

    def availableLines(self):
        STATUS_LINE = 1
        return self.dimensions()['lines'] - STATUS_LINE

    def refresh(self):
        curses.panel.update_panels()
        curses.doupdate()

    def onTop(self):
        logging.info('put {0} view on top'.format(self.__class__.__name__))
        self._panel.top()
        curses.panel.update_panels()
        curses.doupdate()

    def clearScreen(self):
        self._window.erase()
        self._window.move(0, 0)

    def writeLine(self, thing, line):
        self._window.addstr(line, 0, str(thing))

    def dimensions(self):
        lines, columns = self._window.getmaxyx()
        return {'lines': lines, 'columns': columns}

Use 'erase' to clear the screen

Response:
<REPLACE_OLD> self._window.clear()
 <REPLACE_NEW> self._window.erase()
 <REPLACE_END> <|endoftext|> import time
import curses
import curses.panel
import logging

class Base(object):
    def __init__(self, window):
        lines, columns = window.getmaxyx()
        self._window = curses.newwin(lines, columns)
        self._panel = curses.panel.new_panel(self._window)

    def writeStatusLine(self, measurements):
        line = 'time: {0}| {1} measurements, at most {2} visible'.format(time.asctime(), len(measurements), self.availableLines())
        columns = self.dimensions()['columns']
        self._window.addstr(0, 0, line.ljust(columns), curses.A_REVERSE)

    def availableLines(self):
        STATUS_LINE = 1
        return self.dimensions()['lines'] - STATUS_LINE

    def refresh(self):
        curses.panel.update_panels()
        curses.doupdate()

    def onTop(self):
        logging.info('put {0} view on top'.format(self.__class__.__name__))
        self._panel.top()
        curses.panel.update_panels()
        curses.doupdate()

    def clearScreen(self):
        self._window.erase()
        self._window.move(0, 0)

    def writeLine(self, thing, line):
        self._window.addstr(line, 0, str(thing))

    def dimensions(self):
        lines, columns = self._window.getmaxyx()
        return {'lines': lines, 'columns': columns}

Prompt:
tools/scyllatop: Use 'erase' to clear the screen

The 'clear' function explicitly clears the screen and repaints it which
causes really annoying flicker. Use 'erase' to make scyllatop more
pleasant on the eyes.

Message-Id: <2bf04f96d7d510dddf38de01959db6b168f25a31@scylladb.com>

import time
import curses
import curses.panel
import logging

class Base(object):
    def __init__(self, window):
        lines, columns = window.getmaxyx()
        self._window = curses.newwin(lines, columns)
        self._panel = curses.panel.new_panel(self._window)

    def writeStatusLine(self, measurements):
        line = 'time: {0}| {1} measurements, at most {2} visible'.format(time.asctime(), len(measurements), self.availableLines())
        columns = self.dimensions()['columns']
        self._window.addstr(0, 0, line.ljust(columns), curses.A_REVERSE)

    def availableLines(self):
        STATUS_LINE = 1
        return self.dimensions()['lines'] - STATUS_LINE

    def refresh(self):
        curses.panel.update_panels()
        curses.doupdate()

    def onTop(self):
        logging.info('put {0} view on top'.format(self.__class__.__name__))
        self._panel.top()
        curses.panel.update_panels()
        curses.doupdate()

    def clearScreen(self):
        self._window.clear()
        self._window.move(0, 0)

    def writeLine(self, thing, line):
        self._window.addstr(line, 0, str(thing))

    def dimensions(self):
        lines, columns = self._window.getmaxyx()
        return {'lines': lines, 'columns': columns}


# coding: utf-8
from __future__ import unicode_literals

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module

def load_test_module():
    """
    Import test module and trigger registration of tests. Test module is
    defined in `SMOKE_TESTS` setting.
    """

    test_module = getattr(settings, 'SMOKE_TESTS')

    if not test_module:
        raise ImproperlyConfigured('Missing SMOKE_TESTS in settings.')

    try:
        import_module(test_module)
    except ImportError as e:
        msg = "Can't import '{0}' module. Exception: {1}"
        raise ImproperlyConfigured(msg.format(test_module, e))

Fix import of import_module for Py2.6

Fix import of import_module for Py2.6

Response:
<REPLACE_OLD> unicode_literals
from importlib import import_module

from <REPLACE_NEW> unicode_literals

from <REPLACE_END> <REPLACE_OLD> ImproperlyConfigured

def <REPLACE_NEW> ImproperlyConfigured
from django.utils.importlib import import_module

def <REPLACE_END> <|endoftext|> # coding: utf-8
from __future__ import unicode_literals

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module

def load_test_module():
    """
    Import test module and trigger registration of tests. Test module is
    defined in `SMOKE_TESTS` setting.
    """

    test_module = getattr(settings, 'SMOKE_TESTS')

    if not test_module:
        raise ImproperlyConfigured('Missing SMOKE_TESTS in settings.')

    try:
        import_module(test_module)
    except ImportError as e:
        msg = "Can't import '{0}' module. Exception: {1}"
        raise ImproperlyConfigured(msg.format(test_module, e))

Prompt:
Fix import of import_module for Py2.6

# coding: utf-8
from __future__ import unicode_literals
from importlib import import_module

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured

def load_test_module():
    """
    Import test module and trigger registration of tests. Test module is
    defined in `SMOKE_TESTS` setting.
    """

    test_module = getattr(settings, 'SMOKE_TESTS')

    if not test_module:
        raise ImproperlyConfigured('Missing SMOKE_TESTS in settings.')

    try:
        import_module(test_module)
    except ImportError as e:
        msg = "Can't import '{0}' module. Exception: {1}"
        raise ImproperlyConfigured(msg.format(test_module, e))


"""Convenience functions for matplotlib plotting and image viewing."""
import numpy as np
from matplotlib import pyplot as plt

def show(image, blocking=False, title='', **kwargs):
    """Show *image*. If *blocking* is False the call is nonblocking. *title*
    is the image title.  *kwargs* are passed to matplotlib's ``imshow``
    function. This command always creates a new figure. Returns matplotlib's
    ``AxesImage``.
    """
    plt.figure()
    mpl_image = plt.imshow(image, **kwargs)
    plt.colorbar(ticks=np.linspace(image.min(), image.max(), 8))
    plt.title(title)
    plt.show(blocking)

    return mpl_image

def plot(*args, **kwargs):
    """Plot using matplotlib's ``plot`` function. Pass it *args* and *kwargs*.
    *kwargs* are infected with *blocking* and if False or not specified,
    the call is nonblocking. *title* is also alowed to be in *kwargs* which
    sets the figure title. This command always creates a new figure. Returns
    a list of ``Line2D`` instances.
    """
    blocking = kwargs.pop('blocking', False)
    title = kwargs.pop('title', '')

    plt.figure()
    lines = plt.plot(*args, **kwargs)
    plt.title(title)
    plt.show(blocking)

    return lines

Use pop for getting blocking parameter

Use pop for getting blocking parameter

Response:
<REPLACE_OLD> False if 'blocking' not in kwargs else kwargs.pop('blocking')
 <REPLACE_NEW> kwargs.pop('blocking', False)
 <REPLACE_END> <|endoftext|> """Convenience functions for matplotlib plotting and image viewing."""
import numpy as np
from matplotlib import pyplot as plt

def show(image, blocking=False, title='', **kwargs):
    """Show *image*. If *blocking* is False the call is nonblocking. *title*
    is the image title.  *kwargs* are passed to matplotlib's ``imshow``
    function. This command always creates a new figure. Returns matplotlib's
    ``AxesImage``.
    """
    plt.figure()
    mpl_image = plt.imshow(image, **kwargs)
    plt.colorbar(ticks=np.linspace(image.min(), image.max(), 8))
    plt.title(title)
    plt.show(blocking)

    return mpl_image

def plot(*args, **kwargs):
    """Plot using matplotlib's ``plot`` function. Pass it *args* and *kwargs*.
    *kwargs* are infected with *blocking* and if False or not specified,
    the call is nonblocking. *title* is also alowed to be in *kwargs* which
    sets the figure title. This command always creates a new figure. Returns
    a list of ``Line2D`` instances.
    """
    blocking = kwargs.pop('blocking', False)
    title = kwargs.pop('title', '')

    plt.figure()
    lines = plt.plot(*args, **kwargs)
    plt.title(title)
    plt.show(blocking)

    return lines

Prompt:
Use pop for getting blocking parameter

"""Convenience functions for matplotlib plotting and image viewing."""
import numpy as np
from matplotlib import pyplot as plt

def show(image, blocking=False, title='', **kwargs):
    """Show *image*. If *blocking* is False the call is nonblocking. *title*
    is the image title.  *kwargs* are passed to matplotlib's ``imshow``
    function. This command always creates a new figure. Returns matplotlib's
    ``AxesImage``.
    """
    plt.figure()
    mpl_image = plt.imshow(image, **kwargs)
    plt.colorbar(ticks=np.linspace(image.min(), image.max(), 8))
    plt.title(title)
    plt.show(blocking)

    return mpl_image

def plot(*args, **kwargs):
    """Plot using matplotlib's ``plot`` function. Pass it *args* and *kwargs*.
    *kwargs* are infected with *blocking* and if False or not specified,
    the call is nonblocking. *title* is also alowed to be in *kwargs* which
    sets the figure title. This command always creates a new figure. Returns
    a list of ``Line2D`` instances.
    """
    blocking = False if 'blocking' not in kwargs else kwargs.pop('blocking')
    title = kwargs.pop('title', '')

    plt.figure()
    lines = plt.plot(*args, **kwargs)
    plt.title(title)
    plt.show(blocking)

    return lines


"""Add application.properties to Application's S3 Bucket directory."""
import logging
import argparse
from .create_archaius import init_properties

LOG = logging.getLogger(__name__)

def main():
    """Create application.properties for a given application."""
    logging.basicConfig()
    parser = argparse.ArgumentParser(description=main.__doc__)

    parser.add_argument('-d',
                        '--debug',
                        action='store_const',
                        const=logging.DEBUG,
                        default=logging.INFO,
                        help='Set DEBUG output')
    parser.add_argument('-e',
                        '--env',
                        choices=('build', 'dev', 'stage', 'prod'),
                        default='dev',
                        help='Deploy environment')
    parser.add_argument('-g',
                        '--group',
                        default='extra',
                        help='Application Group name, e.g. forrest')
    parser.add_argument('-a',
                        '--app',
                        default='unnecessary',
                        help='Application name, e.g. forrestcore')
    args = parser.parse_args()

    LOG.setLevel(args.debug)
    logging.getLogger(__package__).setLevel(args.debug)
    vars(args).pop('debug')

    LOG.debug('Args: %s', vars(args))

    init_properties(env=args.env, group=args.group, app=args.app)

if __name__ == '__main__':
    main()

Response:
<REPLACE_OLD> choices=('dev', <REPLACE_NEW> choices=('build', 'dev', <REPLACE_END> <|endoftext|> """Add application.properties to Application's S3 Bucket directory."""
import logging
import argparse
from .create_archaius import init_properties

LOG = logging.getLogger(__name__)

def main():
    """Create application.properties for a given application."""
    logging.basicConfig()
    parser = argparse.ArgumentParser(description=main.__doc__)

    parser.add_argument('-d',
                        '--debug',
                        action='store_const',
                        const=logging.DEBUG,
                        default=logging.INFO,
                        help='Set DEBUG output')
    parser.add_argument('-e',
                        '--env',
                        choices=('build', 'dev', 'stage', 'prod'),
                        default='dev',
                        help='Deploy environment')
    parser.add_argument('-g',
                        '--group',
                        default='extra',
                        help='Application Group name, e.g. forrest')
    parser.add_argument('-a',
                        '--app',
                        default='unnecessary',
                        help='Application name, e.g. forrestcore')
    args = parser.parse_args()

    LOG.setLevel(args.debug)
    logging.getLogger(__package__).setLevel(args.debug)
    vars(args).pop('debug')

    LOG.debug('Args: %s', vars(args))

    init_properties(env=args.env, group=args.group, app=args.app)

if __name__ == '__main__':
    main()

Prompt:
Add build as a possible environment option

"""Add application.properties to Application's S3 Bucket directory."""
import logging
import argparse
from .create_archaius import init_properties

LOG = logging.getLogger(__name__)

def main():
    """Create application.properties for a given application."""
    logging.basicConfig()
    parser = argparse.ArgumentParser(description=main.__doc__)

    parser.add_argument('-d',
                        '--debug',
                        action='store_const',
                        const=logging.DEBUG,
                        default=logging.INFO,
                        help='Set DEBUG output')
    parser.add_argument('-e',
                        '--env',
                        choices=('dev', 'stage', 'prod'),
                        default='dev',
                        help='Deploy environment')
    parser.add_argument('-g',
                        '--group',
                        default='extra',
                        help='Application Group name, e.g. forrest')
    parser.add_argument('-a',
                        '--app',
                        default='unnecessary',
                        help='Application name, e.g. forrestcore')
    args = parser.parse_args()

    LOG.setLevel(args.debug)
    logging.getLogger(__package__).setLevel(args.debug)
    vars(args).pop('debug')

    LOG.debug('Args: %s', vars(args))

    init_properties(env=args.env, group=args.group, app=args.app)

if __name__ == '__main__':
    main()


# Copyright (c) 2015, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt

from __future__ import unicode_literals
import frappe

def execute():
	for p in frappe.get_all("Project", filters={"docstatus": 0}):
		project = frappe.get_doc("Project", p.name)
		project.update_purchase_costing()
		project.save()

Response:
<REPLACE_OLD> frappe.get_all("Project"):
		project <REPLACE_NEW> frappe.get_all("Project", filters={"docstatus": 0}):
		project <REPLACE_END> <|endoftext|> # Copyright (c) 2015, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt

from __future__ import unicode_literals
import frappe

def execute():
	for p in frappe.get_all("Project", filters={"docstatus": 0}):
		project = frappe.get_doc("Project", p.name)
		project.update_purchase_costing()
		project.save()

Prompt:
[fix] Update project cost for draft project only

# Copyright (c) 2015, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt

from __future__ import unicode_literals
import frappe

def execute():
	for p in frappe.get_all("Project"):
		project = frappe.get_doc("Project", p.name)
		project.update_purchase_costing()
		project.save()


import sys

from django.conf import settings
from django.test.utils import setup_test_environment, teardown_test_environment

import nose
from nose.config import Config, all_config_files
from nose.plugins.manager import DefaultPluginManager

def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]):
    """ Run tests with nose instead of defualt test runner """
    setup_test_environment()

    from django.db import connection
    old_name = settings.DATABASE_NAME
    connection.creation.create_test_db(verbosity, autoclobber=not interactive)
    argv_backup = sys.argv

    # we have to strip script name before passing to nose
    sys.argv = argv_backup[0:1]
    config = Config(files=all_config_files(), plugins=DefaultPluginManager())

    nose.run(config=config)

    sys.argv = argv_backup
    connection.creation.destroy_test_db(old_name, verbosity)
    teardown_test_environment()

    #TODO: return len(result.failures) + len(result.errors)

run_tests.__test__ = False

Response:
<REPLACE_OLD> from <REPLACE_NEW> import sys

from django.conf import settings
from <REPLACE_END> <REPLACE_OLD> teardown_test_environment
from django.db.backends.creation <REPLACE_NEW> teardown_test_environment

import nose
from nose.config <REPLACE_END> <REPLACE_OLD> create_test_db, destroy_test_db
import nose

def <REPLACE_NEW> Config, all_config_files
from nose.plugins.manager import DefaultPluginManager

def <REPLACE_END> <REPLACE_OLD> setup_test_environment()
 <REPLACE_NEW> setup_test_environment()

    from django.db import connection
 <REPLACE_END> <REPLACE_OLD> create_test_db(verbosity, <REPLACE_NEW> connection.creation.create_test_db(verbosity, <REPLACE_END> <REPLACE_OLD> sys.argv
 <REPLACE_NEW> sys.argv

 <REPLACE_END> <REPLACE_OLD> plugins=DefaultPluginManager())
 <REPLACE_NEW> plugins=DefaultPluginManager())

 <REPLACE_END> <REPLACE_OLD> nose.run(config=config)
 <REPLACE_NEW> nose.run(config=config)

 <REPLACE_END> <REPLACE_OLD> destroy_test_db(old_name, <REPLACE_NEW> connection.creation.destroy_test_db(old_name, <REPLACE_END> <REPLACE_OLD> teardown_test_environment()

run_tests.__test__ <REPLACE_NEW> teardown_test_environment()

    #TODO: return len(result.failures) + len(result.errors)

run_tests.__test__ <REPLACE_END> <|endoftext|> import sys

from django.conf import settings
from django.test.utils import setup_test_environment, teardown_test_environment

import nose
from nose.config import Config, all_config_files
from nose.plugins.manager import DefaultPluginManager

def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]):
    """ Run tests with nose instead of defualt test runner """
    setup_test_environment()

    from django.db import connection
    old_name = settings.DATABASE_NAME
    connection.creation.create_test_db(verbosity, autoclobber=not interactive)
    argv_backup = sys.argv

    # we have to strip script name before passing to nose
    sys.argv = argv_backup[0:1]
    config = Config(files=all_config_files(), plugins=DefaultPluginManager())

    nose.run(config=config)

    sys.argv = argv_backup
    connection.creation.destroy_test_db(old_name, verbosity)
    teardown_test_environment()

    #TODO: return len(result.failures) + len(result.errors)

run_tests.__test__ = False

Prompt:
Use database connection instead of old-style functions

from django.test.utils import setup_test_environment, teardown_test_environment
from django.db.backends.creation import create_test_db, destroy_test_db
import nose

def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]):
    """ Run tests with nose instead of defualt test runner """
    setup_test_environment()
    old_name = settings.DATABASE_NAME
    create_test_db(verbosity, autoclobber=not interactive)
    argv_backup = sys.argv
    # we have to strip script name before passing to nose
    sys.argv = argv_backup[0:1]
    config = Config(files=all_config_files(), plugins=DefaultPluginManager())
    nose.run(config=config)
    sys.argv = argv_backup
    destroy_test_db(old_name, verbosity)
    teardown_test_environment()

run_tests.__test__ = False


#
# linter.py
# Markdown Linter for SublimeLinter, a code checking framework
# for Sublime Text 3
#
# Written by Jon LaBelle
# Copyright (c) 2018 Jon LaBelle
#
# License: MIT
#

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

from SublimeLinter.lint import NodeLinter, util

class MarkdownLint(NodeLinter):
    """Provides an interface to markdownlint."""

    syntax = ('markdown', 'markdown gfm', 'multimarkdown', 'markdown extended')
    cmd = ('markdownlint', '${args}', '${file}')
    npm_name = 'markdownlint'
    config_file = ('--config', '.markdownlintrc')
    regex = r'.+?[:]\s(?P<line>\d+)[:]\s(?P<error>MD\d+)?[/]?(?P<message>.+)'
    multiline = False
    line_col_base = (1, 1)
    tempfile_suffix = '-'
    error_stream = util.STREAM_STDERR
    word_re = None
    comment_re = r'\s*/[/*]'

Response:
<DELETE> version_args = '--version'
    version_re = r'(?P<version>\d+\.\d+\.\d+)'
    version_requirement = '>= 0.6.0'
    check_version = True
    <DELETE_END> <|endoftext|> #
# linter.py
# Markdown Linter for SublimeLinter, a code checking framework
# for Sublime Text 3
#
# Written by Jon LaBelle
# Copyright (c) 2018 Jon LaBelle
#
# License: MIT
#

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

from SublimeLinter.lint import NodeLinter, util

class MarkdownLint(NodeLinter):
    """Provides an interface to markdownlint."""

    syntax = ('markdown', 'markdown gfm', 'multimarkdown', 'markdown extended')
    cmd = ('markdownlint', '${args}', '${file}')
    npm_name = 'markdownlint'
    config_file = ('--config', '.markdownlintrc')
    regex = r'.+?[:]\s(?P<line>\d+)[:]\s(?P<error>MD\d+)?[/]?(?P<message>.+)'
    multiline = False
    line_col_base = (1, 1)
    tempfile_suffix = '-'
    error_stream = util.STREAM_STDERR
    word_re = None
    comment_re = r'\s*/[/*]'

Prompt:
Remove deprecated version requirement settings

Linter plugins can no longer set version requirements.
https://github.com/SublimeLinter/SublimeLinter/issues/1087
#
# linter.py
# Markdown Linter for SublimeLinter, a code checking framework
# for Sublime Text 3
#
# Written by Jon LaBelle
# Copyright (c) 2018 Jon LaBelle
#
# License: MIT
#

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

from SublimeLinter.lint import NodeLinter, util

class MarkdownLint(NodeLinter):
    """Provides an interface to markdownlint."""

    syntax = ('markdown', 'markdown gfm', 'multimarkdown', 'markdown extended')
    cmd = ('markdownlint', '${args}', '${file}')
    npm_name = 'markdownlint'
    config_file = ('--config', '.markdownlintrc')
    version_args = '--version'
    version_re = r'(?P<version>\d+\.\d+\.\d+)'
    version_requirement = '>= 0.6.0'
    check_version = True
    regex = r'.+?[:]\s(?P<line>\d+)[:]\s(?P<error>MD\d+)?[/]?(?P<message>.+)'
    multiline = False
    line_col_base = (1, 1)
    tempfile_suffix = '-'
    error_stream = util.STREAM_STDERR
    word_re = None
    comment_re = r'\s*/[/*]'


import random

import discord
from discord.ext import commands

class MyContext(commands.Context):
    async def tick(self, value):
        # reacts to the message with an emoji
        # depending on whether value is True or False
        # if its True, it'll add a green check mark
        # otherwise, it'll add a red cross mark
        emoji = '\N{WHITE HEAVY CHECK MARK}' if value else '\N{CROSS MARK}'
        try:
            # this will react to the command author's message
            await self.message.add_reaction(emoji)
        except discord.HTTPException:
            # sometimes errors occur during this, for example
            # maybe you dont have permission to do that
            # we dont mind, so we can just ignore them
            pass

class MyBot(commands.Bot):
    async def get_context(self, message, *, cls=MyContext):
        # when you override this method, you pass your new Context
        # subclass to the super() method, which tells the bot to
        # use the new MyContext class
        return await super().get_context(message, cls=cls)

bot = MyBot(command_prefix='!')

@bot.command()
async def guess(ctx, number: int):
    """ Guess a random number from 1 to 6. """
    # explained in a previous example, this gives you
    # a random number from 1-6
    value = random.randint(1, 6)
    # with your new helper function, you can add a
    # green check mark if the guess was correct,
    # or a red cross mark if it wasnt
    await ctx.tick(number == value)

# important: you shouldnt hard code your token
# these are very important, and leaking them can
# let people do very malicious things with your
# bot. try to use a file or something to keep
# them private, and dont commit it to GitHub
token = "your token here"
bot.run(token)

Add example on subclassing commands.Context

Response:
<REPLACE_OLD>  <REPLACE_NEW> import random

import discord
from discord.ext import commands

class MyContext(commands.Context):
    async def tick(self, value):
        # reacts to the message with an emoji
        # depending on whether value is True or False
        # if its True, it'll add a green check mark
        # otherwise, it'll add a red cross mark
        emoji = '\N{WHITE HEAVY CHECK MARK}' if value else '\N{CROSS MARK}'
        try:
            # this will react to the command author's message
            await self.message.add_reaction(emoji)
        except discord.HTTPException:
            # sometimes errors occur during this, for example
            # maybe you dont have permission to do that
            # we dont mind, so we can just ignore them
            pass

class MyBot(commands.Bot):
    async def get_context(self, message, *, cls=MyContext):
        # when you override this method, you pass your new Context
        # subclass to the super() method, which tells the bot to
        # use the new MyContext class
        return await super().get_context(message, cls=cls)

bot = MyBot(command_prefix='!')

@bot.command()
async def guess(ctx, number: int):
    """ Guess a random number from 1 to 6. """
    # explained in a previous example, this gives you
    # a random number from 1-6
    value = random.randint(1, 6)
    # with your new helper function, you can add a
    # green check mark if the guess was correct,
    # or a red cross mark if it wasnt
    await ctx.tick(number == value)

# important: you shouldnt hard code your token
# these are very important, and leaking them can
# let people do very malicious things with your
# bot. try to use a file or something to keep
# them private, and dont commit it to GitHub
token = "your token here"
bot.run(token)
 <REPLACE_END> <|endoftext|> import random

import discord
from discord.ext import commands

class MyContext(commands.Context):
    async def tick(self, value):
        # reacts to the message with an emoji
        # depending on whether value is True or False
        # if its True, it'll add a green check mark
        # otherwise, it'll add a red cross mark
        emoji = '\N{WHITE HEAVY CHECK MARK}' if value else '\N{CROSS MARK}'
        try:
            # this will react to the command author's message
            await self.message.add_reaction(emoji)
        except discord.HTTPException:
            # sometimes errors occur during this, for example
            # maybe you dont have permission to do that
            # we dont mind, so we can just ignore them
            pass

class MyBot(commands.Bot):
    async def get_context(self, message, *, cls=MyContext):
        # when you override this method, you pass your new Context
        # subclass to the super() method, which tells the bot to
        # use the new MyContext class
        return await super().get_context(message, cls=cls)

bot = MyBot(command_prefix='!')

@bot.command()
async def guess(ctx, number: int):
    """ Guess a random number from 1 to 6. """
    # explained in a previous example, this gives you
    # a random number from 1-6
    value = random.randint(1, 6)
    # with your new helper function, you can add a
    # green check mark if the guess was correct,
    # or a red cross mark if it wasnt
    await ctx.tick(number == value)

# important: you shouldnt hard code your token
# these are very important, and leaking them can
# let people do very malicious things with your
# bot. try to use a file or something to keep
# them private, and dont commit it to GitHub
token = "your token here"
bot.run(token)

Prompt: Add example on subclassing commands.Context


#!/usr/bin/env python
"""
Convert the output of ms to an N-dimensional frequency spectrum.
"""
import sys

import dadi

if __name__ == '__main__':
    average = ('-av' in sys.argv)

    input = sys.stdin
    output = sys.stdout
    sfs,header = dadi.Spectrum.from_ms_file(input, average, mask_corners=True,
                                            return_header=True)

    dadi.IO.sfs_to_file(sfs, output, comment_lines=header)

Rename so we can import it and thus get useful epydoc documentation.

git-svn-id: 4c7b13231a96299fde701bb5dec4bd2aaf383fc6@132 979d6bd5-6d4d-0410-bece-f567c23bd345

Response:
<INSERT> #!/usr/bin/env python
"""
Convert the output of ms to an N-dimensional frequency spectrum.
"""
import sys

import dadi

if __name__ == '__main__':
 <INSERT_END> <INSERT>   average = ('-av' in sys.argv)

    input = sys.stdin
    output = sys.stdout
    sfs,header = dadi.Spectrum.from_ms_file(input, average, mask_corners=True,
                                            return_header=True)

    dadi.IO.sfs_to_file(sfs, output, comment_lines=header)
 <INSERT_END> <|endoftext|> #!/usr/bin/env python
"""
Convert the output of ms to an N-dimensional frequency spectrum.
"""
import sys

import dadi

if __name__ == '__main__':
    average = ('-av' in sys.argv)

    input = sys.stdin
    output = sys.stdout
    sfs,header = dadi.Spectrum.from_ms_file(input, average, mask_corners=True,
                                            return_header=True)

    dadi.IO.sfs_to_file(sfs, output, comment_lines=header)

Prompt:
Rename so we can import it and thus get useful epydoc documentation.

git-svn-id: 4c7b13231a96299fde701bb5dec4bd2aaf383fc6@132 979d6bd5-6d4d-0410-bece-f567c23bd345


import unittest

from classes import Paladin
from models.spells.loader import load_paladin_spells_for_level

class PaladinTests(unittest.TestCase):
    def setUp(self):
        self.name = "Netherblood"
        self.level = 3
        self.dummy = Paladin(name=self.name, level=self.level, health=100, mana=100, strength=10)

    def test_init(self):
        """ The __init__ should load/save all the spells for the Paladin"""
        spells = [spell for level in range(1,self.level+1) for spell in load_paladin_spells_for_level(level)]

        self.assertNotEqual(len(self.dummy.learned_spells), 0)
        for spell in spells:
            self.assertIn(spell.name, self.dummy.learned_spells)
            char_spell = self.dummy.learned_spells[spell.name]
            # find the largest rank in our spells list (the char has the highest rank only)
            max_rank = list(sorted(filter(lambda x: x.name == spell.name, spells), key=lambda x: x.rank))[-1].rank

            self.assertEqual(char_spell.rank, max_rank)

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

Test for the __init__ function of the Paladin class

Response:
<REPLACE_OLD>  <REPLACE_NEW> import unittest

from classes import Paladin
from models.spells.loader import load_paladin_spells_for_level

class PaladinTests(unittest.TestCase):
    def setUp(self):
        self.name = "Netherblood"
        self.level = 3
        self.dummy = Paladin(name=self.name, level=self.level, health=100, mana=100, strength=10)

    def test_init(self):
        """ The __init__ should load/save all the spells for the Paladin"""
        spells = [spell for level in range(1,self.level+1) for spell in load_paladin_spells_for_level(level)]

        self.assertNotEqual(len(self.dummy.learned_spells), 0)
        for spell in spells:
            self.assertIn(spell.name, self.dummy.learned_spells)
            char_spell = self.dummy.learned_spells[spell.name]
            # find the largest rank in our spells list (the char has the highest rank only)
            max_rank = list(sorted(filter(lambda x: x.name == spell.name, spells), key=lambda x: x.rank))[-1].rank

            self.assertEqual(char_spell.rank, max_rank)

if __name__ == '__main__':
    unittest.main()
 <REPLACE_END> <|endoftext|> import unittest

from classes import Paladin
from models.spells.loader import load_paladin_spells_for_level

class PaladinTests(unittest.TestCase):
    def setUp(self):
        self.name = "Netherblood"
        self.level = 3
        self.dummy = Paladin(name=self.name, level=self.level, health=100, mana=100, strength=10)

    def test_init(self):
        """ The __init__ should load/save all the spells for the Paladin"""
        spells = [spell for level in range(1,self.level+1) for spell in load_paladin_spells_for_level(level)]

        self.assertNotEqual(len(self.dummy.learned_spells), 0)
        for spell in spells:
            self.assertIn(spell.name, self.dummy.learned_spells)
            char_spell = self.dummy.learned_spells[spell.name]
            # find the largest rank in our spells list (the char has the highest rank only)
            max_rank = list(sorted(filter(lambda x: x.name == spell.name, spells), key=lambda x: x.rank))[-1].rank

            self.assertEqual(char_spell.rank, max_rank)

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

Prompt: Test for the __init__ function of the Paladin class


# -*- coding: utf-8 -*-
# ex:set ts=4 et sw=4 ai:

from gi.repository import GObject, Introspection, Peas

class ExtensionPythonPlugin(GObject.Object, Peas.Activatable,
                            Introspection.Base, Introspection.Callable,
                            Introspection.PropertiesPrerequisite,
                            Introspection.Properties,
                            Introspection.HasPrerequisite):

    object = GObject.property(type=GObject.Object)

    construct_only = GObject.property(type=str)
    read_only = GObject.property(type=str, default="read-only")
    write_only = GObject.property(type=str)
    readwrite = GObject.property(type=str, default="readwrite")
    prerequisite = GObject.property(type=str)

    def do_activate(self):
        pass

    def do_deactivate(self):
        pass

    def do_update_state(self):
        pass

    def do_get_plugin_info(self):
        return self.plugin_info

    def do_get_settings(self):
        return self.plugin_info.get_settings(None)

    def do_call_with_return(self):
        return "Hello, World!"

    def do_call_no_args(self):
        pass

    def do_call_single_arg(self):
        return True

    def do_call_multi_args(self, in_, inout):
        return (inout, in_)

Fix style issues in python test plugin

Response:
<REPLACE_OLD> pass

 <REPLACE_NEW> pass

 <REPLACE_END> <REPLACE_OLD> World!";

 <REPLACE_NEW> World!"

 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
# ex:set ts=4 et sw=4 ai:

from gi.repository import GObject, Introspection, Peas

class ExtensionPythonPlugin(GObject.Object, Peas.Activatable,
                            Introspection.Base, Introspection.Callable,
                            Introspection.PropertiesPrerequisite,
                            Introspection.Properties,
                            Introspection.HasPrerequisite):

    object = GObject.property(type=GObject.Object)

    construct_only = GObject.property(type=str)
    read_only = GObject.property(type=str, default="read-only")
    write_only = GObject.property(type=str)
    readwrite = GObject.property(type=str, default="readwrite")
    prerequisite = GObject.property(type=str)

    def do_activate(self):
        pass

    def do_deactivate(self):
        pass

    def do_update_state(self):
        pass

    def do_get_plugin_info(self):
        return self.plugin_info

    def do_get_settings(self):
        return self.plugin_info.get_settings(None)

    def do_call_with_return(self):
        return "Hello, World!"

    def do_call_no_args(self):
        pass

    def do_call_single_arg(self):
        return True

    def do_call_multi_args(self, in_, inout):
        return (inout, in_)

Prompt:
Fix style issues in python test plugin

https://bugzilla.gnome.org/show_bug.cgi?id=678339
# -*- coding: utf-8 -*-
# ex:set ts=4 et sw=4 ai:

from gi.repository import GObject, Introspection, Peas

class ExtensionPythonPlugin(GObject.Object, Peas.Activatable,
                            Introspection.Base, Introspection.Callable,
                            Introspection.PropertiesPrerequisite,
                            Introspection.Properties,
                            Introspection.HasPrerequisite):

    object = GObject.property(type=GObject.Object)

    construct_only = GObject.property(type=str)
    read_only = GObject.property(type=str, default="read-only")
    write_only = GObject.property(type=str)
    readwrite = GObject.property(type=str, default="readwrite")
    prerequisite = GObject.property(type=str)

    def do_activate(self):
        pass

    def do_deactivate(self):
        pass

    def do_update_state(self):
        pass

    def do_get_plugin_info(self):
        return self.plugin_info

    def do_get_settings(self):
        return self.plugin_info.get_settings(None)

    def do_call_with_return(self):
        return "Hello, World!";

    def do_call_no_args(self):
        pass

    def do_call_single_arg(self):
        return True

    def do_call_multi_args(self, in_, inout):
        return (inout, in_)


"""Configuration for the Caffe2 installation.
"""

from build import Config
import sys

Config.USE_SYSTEM_PROTOBUF = False
Config.PROTOC_BINARY = 'gen/third_party/google/protoc'
Config.USE_OPENMP = False

if __name__ == '__main__':
    from brewtool.brewery import Brewery
    Brewery.Run(
        Config,
        ['build_android_prepare.py',
         'build', '//third_party/google:protoc'])
else:
    print('This script is not intended to be used as an imported module.')
    sys.exit(1)

Add a simple script to help build android.

Response:
<INSERT> """Configuration for the Caffe2 installation.
"""

from build import Config
import sys

Config.USE_SYSTEM_PROTOBUF = False
Config.PROTOC_BINARY = 'gen/third_party/google/protoc'
Config.USE_OPENMP = False

if __name__ == '__main__':
 <INSERT_END> <INSERT>   from brewtool.brewery import Brewery
    Brewery.Run(
        Config,
        ['build_android_prepare.py',
         'build', '//third_party/google:protoc'])
else:
    print('This script is not intended to be used as an imported module.')
    sys.exit(1)
 <INSERT_END> <|endoftext|> """Configuration for the Caffe2 installation.
"""

from build import Config
import sys

Config.USE_SYSTEM_PROTOBUF = False
Config.PROTOC_BINARY = 'gen/third_party/google/protoc'
Config.USE_OPENMP = False

if __name__ == '__main__':
    from brewtool.brewery import Brewery
    Brewery.Run(
        Config,
        ['build_android_prepare.py',
         'build', '//third_party/google:protoc'])
else:
    print('This script is not intended to be used as an imported module.')
    sys.exit(1)

Prompt: Add a simple script to help build android.


def binary_search(array, low, high, item):

    if(low>high) :
        return -1

    mid = (low + high)//2

    if(item == array[mid]):
        return mid
    elif item < array[mid]:
        return binary_search(array, low, mid-1, item)
    elif item > array[mid]:
        return binary_search(array, mid+1, high, item)

print ( binary_search([1,4,5,7], 0, 3, 5)) #2
print ( binary_search([1,4,5,7], 0, 3, 10)) #-1

Add recursive binary search implementation

Response:
<INSERT>
def binary_search(array, low, high, item):

 <INSERT_END> <INSERT>   if(low>high) :
        return -1

    mid = (low + high)//2

    if(item == array[mid]):
        return mid
    elif item < array[mid]:
        return binary_search(array, low, mid-1, item)
    elif item > array[mid]:
        return binary_search(array, mid+1, high, item)

print ( binary_search([1,4,5,7], 0, 3, 5)) #2
print ( binary_search([1,4,5,7], 0, 3, 10)) #-1
 <INSERT_END> <|endoftext|>
def binary_search(array, low, high, item):

    if(low>high) :
        return -1

    mid = (low + high)//2

    if(item == array[mid]):
        return mid
    elif item < array[mid]:
        return binary_search(array, low, mid-1, item)
    elif item > array[mid]:
        return binary_search(array, mid+1, high, item)

print ( binary_search([1,4,5,7], 0, 3, 5)) #2
print ( binary_search([1,4,5,7], 0, 3, 10)) #-1

Prompt: Add recursive binary search implementation