import io
import sys
import tempfile
import textwrap

from jacquard.config import load_config

CONFIG_FILE = """
[storage]
engine = dummy
url = dummy

[directory]
engine = dummy

[test_section]
test_key = test_value
"""

def load_test_config(extra=''):
    f = io.StringIO(CONFIG_FILE + textwrap.dedent(extra))
    return load_config(f)

def test_load_config_smoke():
    load_test_config()

def test_load_config_from_file():
    with tempfile.NamedTemporaryFile('w') as f:
        f.write(CONFIG_FILE)
        f.flush()
        load_config(f.name)

def test_config_creates_storage_engine():
    config = load_test_config()

    with config.storage.transaction() as store:
        store['bees'] = 'pony'

    with config.storage.transaction() as store:
        assert store['bees'] == 'pony'

def test_config_creates_directory():
    config = load_test_config()

    assert list(config.directory.all_users()) == []

def test_config_can_iterate_over_sections():
    config = load_test_config()

    assert set(config) == {'storage', 'directory', 'test_section', 'DEFAULT'}

def test_config_can_query_subsections():
    config = load_test_config()

    assert config['test_section']['test_key'] == 'test_value'

def test_config_can_test_section_inclusion():
    config = load_test_config()

    assert 'test_section' in config
    assert 'test_section2' not in config

def test_config_section_len():
    config = load_test_config()

    assert len(config) == 4

def test_adds_extra_elements_to_path():
    try:
        sys.path.remove('/gravity')
    except ValueError:
        pass

    load_test_config("""
    [paths]
    a_path = /gravity
    """)

    assert '/gravity' in sys.path

Add tests for config loading

Add tests for config loading

Response:
<REPLACE_OLD>  <REPLACE_NEW> import io
import sys
import tempfile
import textwrap

from jacquard.config import load_config

CONFIG_FILE = """
[storage]
engine = dummy
url = dummy

[directory]
engine = dummy

[test_section]
test_key = test_value
"""

def load_test_config(extra=''):
    f = io.StringIO(CONFIG_FILE + textwrap.dedent(extra))
    return load_config(f)

def test_load_config_smoke():
    load_test_config()

def test_load_config_from_file():
    with tempfile.NamedTemporaryFile('w') as f:
        f.write(CONFIG_FILE)
        f.flush()
        load_config(f.name)

def test_config_creates_storage_engine():
    config = load_test_config()

    with config.storage.transaction() as store:
        store['bees'] = 'pony'

    with config.storage.transaction() as store:
        assert store['bees'] == 'pony'

def test_config_creates_directory():
    config = load_test_config()

    assert list(config.directory.all_users()) == []

def test_config_can_iterate_over_sections():
    config = load_test_config()

    assert set(config) == {'storage', 'directory', 'test_section', 'DEFAULT'}

def test_config_can_query_subsections():
    config = load_test_config()

    assert config['test_section']['test_key'] == 'test_value'

def test_config_can_test_section_inclusion():
    config = load_test_config()

    assert 'test_section' in config
    assert 'test_section2' not in config

def test_config_section_len():
    config = load_test_config()

    assert len(config) == 4

def test_adds_extra_elements_to_path():
    try:
        sys.path.remove('/gravity')
    except ValueError:
        pass

    load_test_config("""
    [paths]
    a_path = /gravity
    """)

    assert '/gravity' in sys.path
 <REPLACE_END> <|endoftext|> import io
import sys
import tempfile
import textwrap

from jacquard.config import load_config

CONFIG_FILE = """
[storage]
engine = dummy
url = dummy

[directory]
engine = dummy

[test_section]
test_key = test_value
"""

def load_test_config(extra=''):
    f = io.StringIO(CONFIG_FILE + textwrap.dedent(extra))
    return load_config(f)

def test_load_config_smoke():
    load_test_config()

def test_load_config_from_file():
    with tempfile.NamedTemporaryFile('w') as f:
        f.write(CONFIG_FILE)
        f.flush()
        load_config(f.name)

def test_config_creates_storage_engine():
    config = load_test_config()

    with config.storage.transaction() as store:
        store['bees'] = 'pony'

    with config.storage.transaction() as store:
        assert store['bees'] == 'pony'

def test_config_creates_directory():
    config = load_test_config()

    assert list(config.directory.all_users()) == []

def test_config_can_iterate_over_sections():
    config = load_test_config()

    assert set(config) == {'storage', 'directory', 'test_section', 'DEFAULT'}

def test_config_can_query_subsections():
    config = load_test_config()

    assert config['test_section']['test_key'] == 'test_value'

def test_config_can_test_section_inclusion():
    config = load_test_config()

    assert 'test_section' in config
    assert 'test_section2' not in config

def test_config_section_len():
    config = load_test_config()

    assert len(config) == 4

def test_adds_extra_elements_to_path():
    try:
        sys.path.remove('/gravity')
    except ValueError:
        pass

    load_test_config("""
    [paths]
    a_path = /gravity
    """)

    assert '/gravity' in sys.path

Prompt: Add tests for config loading


"""
ChatterBot is a machine learning, conversational dialog engine.
"""
from .chatterbot import ChatBot

__version__ = '0.5.2'
__author__ = 'Gunther Cox'
__email__ = 'gunthercx@gmail.com'
__url__ = 'https://github.com/gunthercox/ChatterBot'

Update release version to 0.5.2

Update release version to 0.5.2

Response:
<REPLACE_OLD> '0.5.1'
__author__ <REPLACE_NEW> '0.5.2'
__author__ <REPLACE_END> <|endoftext|> """
ChatterBot is a machine learning, conversational dialog engine.
"""
from .chatterbot import ChatBot

__version__ = '0.5.2'
__author__ = 'Gunther Cox'
__email__ = 'gunthercx@gmail.com'
__url__ = 'https://github.com/gunthercox/ChatterBot'

Prompt:
Update release version to 0.5.2

"""
ChatterBot is a machine learning, conversational dialog engine.
"""
from .chatterbot import ChatBot

__version__ = '0.5.1'
__author__ = 'Gunther Cox'
__email__ = 'gunthercx@gmail.com'
__url__ = 'https://github.com/gunthercox/ChatterBot'


#!/usr/bin/env python

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

readme = open('README.rst').read()
history = open('HISTORY.rst').read().replace('.. :changelog:', '')

setup(
    name='binaryornot',
    version='0.4.0',
    description=(
        'Ultra-lightweight pure Python package to check '
        'if a file is binary or text.'
    ),
    long_description=readme + '\n\n' + history,
    author='Audrey Roy Greenfeld',
    author_email='aroy@alum.mit.edu',
    url='https://github.com/audreyr/binaryornot',
    packages=[
        'binaryornot',
    ],
    package_dir={'binaryornot': 'binaryornot'},
    include_package_data=True,
    install_requires=[
        'chardet>=2.0.0',
    ],
    license="BSD",
    zip_safe=False,
    keywords='binaryornot',
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Natural Language :: English',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],
    test_suite='tests',
)

Response:
<REPLACE_OLD> python

try:
 <REPLACE_NEW> python

try:
 <REPLACE_END> <REPLACE_OLD> Roy',
    author_email='audreyr@gmail.com',
 <REPLACE_NEW> Roy Greenfeld',
    author_email='aroy@alum.mit.edu',
 <REPLACE_END> <REPLACE_OLD> 4 <REPLACE_NEW> 5 <REPLACE_END> <REPLACE_OLD> Beta',
 <REPLACE_NEW> Production/Stable',
 <REPLACE_END> <INSERT>     'Programming Language :: Python :: 3.5',
    <INSERT_END> <|endoftext|> #!/usr/bin/env python

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

readme = open('README.rst').read()
history = open('HISTORY.rst').read().replace('.. :changelog:', '')

setup(
    name='binaryornot',
    version='0.4.0',
    description=(
        'Ultra-lightweight pure Python package to check '
        'if a file is binary or text.'
    ),
    long_description=readme + '\n\n' + history,
    author='Audrey Roy Greenfeld',
    author_email='aroy@alum.mit.edu',
    url='https://github.com/audreyr/binaryornot',
    packages=[
        'binaryornot',
    ],
    package_dir={'binaryornot': 'binaryornot'},
    include_package_data=True,
    install_requires=[
        'chardet>=2.0.0',
    ],
    license="BSD",
    zip_safe=False,
    keywords='binaryornot',
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Natural Language :: English',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],
    test_suite='tests',
)

Prompt:
Update trove classifier to Stable. Update my info.

#!/usr/bin/env python

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

readme = open('README.rst').read()
history = open('HISTORY.rst').read().replace('.. :changelog:', '')

setup(
    name='binaryornot',
    version='0.4.0',
    description=(
        'Ultra-lightweight pure Python package to check '
        'if a file is binary or text.'
    ),
    long_description=readme + '\n\n' + history,
    author='Audrey Roy',
    author_email='audreyr@gmail.com',
    url='https://github.com/audreyr/binaryornot',
    packages=[
        'binaryornot',
    ],
    package_dir={'binaryornot': 'binaryornot'},
    include_package_data=True,
    install_requires=[
        'chardet>=2.0.0',
    ],
    license="BSD",
    zip_safe=False,
    keywords='binaryornot',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Natural Language :: English',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
    ],
    test_suite='tests',
)


from cycy import compiler
from cycy.parser.sourceparser import parse

class CyCy(object):
    """
    The main CyCy interpreter.
    """

    def run(self, bytecode):
        pass

def interpret(source):
    bytecode = compiler.Context.to_bytecode(parse(source))
    CyCy().run(bytecode)

Response:
<DELETE> print "Hello, world!"
    return

    <DELETE_END> <REPLACE_OLD> compiler.Context.to_bytecode(parse(source.getContent()))
 <REPLACE_NEW> compiler.Context.to_bytecode(parse(source))
 <REPLACE_END> <|endoftext|> from cycy import compiler
from cycy.parser.sourceparser import parse

class CyCy(object):
    """
    The main CyCy interpreter.
    """

    def run(self, bytecode):
        pass

def interpret(source):
    bytecode = compiler.Context.to_bytecode(parse(source))
    CyCy().run(bytecode)

Prompt:
Break the tests to show us we're not writing RPython.

from cycy import compiler
from cycy.parser.sourceparser import parse

class CyCy(object):
    """
    The main CyCy interpreter.
    """

    def run(self, bytecode):
        pass

def interpret(source):
    print "Hello, world!"
    return

    bytecode = compiler.Context.to_bytecode(parse(source.getContent()))
    CyCy().run(bytecode)


import re
import py.code
import pytest

def pytest_namespace():
    return {'raises_regexp': raises_regexp}

class raises_regexp(object):
    def __init__(self, expected_exception, regexp):
        self.exception = expected_exception
        self.regexp = regexp
        self.excinfo = None

    def __enter__(self):
        self.excinfo = object.__new__(py.code.ExceptionInfo)
        return self.excinfo

    def __exit__(self, exc_type, exc_val, exc_tb):
        __tracebackhide__ = True
        if exc_type is None:
            pytest.fail('DID NOT RAISE %s' % self.exception)

        self.excinfo.__init__((exc_type, exc_val, exc_tb))

        if not issubclass(exc_type, self.exception):
            pytest.fail('%s RAISED instead of %s\n%s' % (exc_type, self.exception, repr(exc_val)))

        if not re.search(self.regexp, str(exc_val)):
            pytest.fail('pattern "%s" not found in "%s"' % (self.regexp, str(exc_val)))

        return True

Response:
<REPLACE_OLD> %s' <REPLACE_NEW> %s\n%s' <REPLACE_END> <REPLACE_OLD> self.exception))

 <REPLACE_NEW> self.exception, repr(exc_val)))

 <REPLACE_END> <|endoftext|> import re
import py.code
import pytest

def pytest_namespace():
    return {'raises_regexp': raises_regexp}

class raises_regexp(object):
    def __init__(self, expected_exception, regexp):
        self.exception = expected_exception
        self.regexp = regexp
        self.excinfo = None

    def __enter__(self):
        self.excinfo = object.__new__(py.code.ExceptionInfo)
        return self.excinfo

    def __exit__(self, exc_type, exc_val, exc_tb):
        __tracebackhide__ = True
        if exc_type is None:
            pytest.fail('DID NOT RAISE %s' % self.exception)

        self.excinfo.__init__((exc_type, exc_val, exc_tb))

        if not issubclass(exc_type, self.exception):
            pytest.fail('%s RAISED instead of %s\n%s' % (exc_type, self.exception, repr(exc_val)))

        if not re.search(self.regexp, str(exc_val)):
            pytest.fail('pattern "%s" not found in "%s"' % (self.regexp, str(exc_val)))

        return True

Prompt:
Add originally raised exception value to pytest error message

import re
import py.code
import pytest

def pytest_namespace():
    return {'raises_regexp': raises_regexp}

class raises_regexp(object):
    def __init__(self, expected_exception, regexp):
        self.exception = expected_exception
        self.regexp = regexp
        self.excinfo = None

    def __enter__(self):
        self.excinfo = object.__new__(py.code.ExceptionInfo)
        return self.excinfo

    def __exit__(self, exc_type, exc_val, exc_tb):
        __tracebackhide__ = True
        if exc_type is None:
            pytest.fail('DID NOT RAISE %s' % self.exception)

        self.excinfo.__init__((exc_type, exc_val, exc_tb))

        if not issubclass(exc_type, self.exception):
            pytest.fail('%s RAISED instead of %s' % (exc_type, self.exception))

        if not re.search(self.regexp, str(exc_val)):
            pytest.fail('pattern "%s" not found in "%s"' % (self.regexp, str(exc_val)))

        return True


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

from flask import Flask
from flask_split import split
from flask_split.core import _get_redis_connection

class TestCase(object):
    def setup_method(self, method):
        self.app = Flask(__name__)
        self.app.debug = True
        self.app.secret_key = 'very secret'
        self.app.register_blueprint(split)
        self._ctx = self.make_test_request_context()
        self._ctx.push()
        self.redis = _get_redis_connection()
        self.redis.flushall()
        self.client = self.app.test_client()

    def teardown_method(self, method):
        self._ctx.pop()

    def make_test_request_context(self):
        return self.app.test_request_context()

def assert_redirects(response, location):
    """
    Checks if response is an HTTP redirect to the
    given location.

    :param response: Flask response
    :param location: relative URL (i.e. without **http://localhost**)
    """
    assert response.status_code in (301, 302)
    assert response.location == 'http://localhost' + location

Fix redis initialization in tests

Fix redis initialization in tests

Response:
<REPLACE_OLD> redis <REPLACE_NEW> flask_split.core <REPLACE_END> <REPLACE_OLD> Redis

class <REPLACE_NEW> _get_redis_connection

class <REPLACE_END> <DELETE>        self.redis = Redis()
        self.redis.flushall()
 <DELETE_END> <INSERT>        self.redis = _get_redis_connection()
        self.redis.flushall()
 <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-

from flask import Flask
from flask_split import split
from flask_split.core import _get_redis_connection

class TestCase(object):
    def setup_method(self, method):
        self.app = Flask(__name__)
        self.app.debug = True
        self.app.secret_key = 'very secret'
        self.app.register_blueprint(split)
        self._ctx = self.make_test_request_context()
        self._ctx.push()
        self.redis = _get_redis_connection()
        self.redis.flushall()
        self.client = self.app.test_client()

    def teardown_method(self, method):
        self._ctx.pop()

    def make_test_request_context(self):
        return self.app.test_request_context()

def assert_redirects(response, location):
    """
    Checks if response is an HTTP redirect to the
    given location.

    :param response: Flask response
    :param location: relative URL (i.e. without **http://localhost**)
    """
    assert response.status_code in (301, 302)
    assert response.location == 'http://localhost' + location

Prompt:
Fix redis initialization in tests

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

from flask import Flask
from flask_split import split
from redis import Redis

class TestCase(object):
    def setup_method(self, method):
        self.redis = Redis()
        self.redis.flushall()
        self.app = Flask(__name__)
        self.app.debug = True
        self.app.secret_key = 'very secret'
        self.app.register_blueprint(split)
        self._ctx = self.make_test_request_context()
        self._ctx.push()
        self.client = self.app.test_client()

    def teardown_method(self, method):
        self._ctx.pop()

    def make_test_request_context(self):
        return self.app.test_request_context()

def assert_redirects(response, location):
    """
    Checks if response is an HTTP redirect to the
    given location.

    :param response: Flask response
    :param location: relative URL (i.e. without **http://localhost**)
    """
    assert response.status_code in (301, 302)
    assert response.location == 'http://localhost' + location


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

def read(fname):
    try:
        return open(os.path.join(os.path.dirname(__file__), fname)).read()
    except:
        return ''

setup(
    name='todoist-python',
    version='7.0.14',
    packages=['todoist', 'todoist.managers'],
    author='Doist Team',
    author_email='info@todoist.com',
    license='BSD',
    description='todoist-python - The official Todoist Python API library',
    long_description = read('README.md'),
    install_requires=[
        'requests',
    ],
    # see here for complete list of classifiers
    # http://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=(
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Programming Language :: Python',
    ),
)

Update the PyPI version to 7.0.14.

Update the PyPI version to 7.0.14.

Response:
<REPLACE_OLD> version='7.0.13',
 <REPLACE_NEW> version='7.0.14',
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
import os
from setuptools import setup

def read(fname):
    try:
        return open(os.path.join(os.path.dirname(__file__), fname)).read()
    except:
        return ''

setup(
    name='todoist-python',
    version='7.0.14',
    packages=['todoist', 'todoist.managers'],
    author='Doist Team',
    author_email='info@todoist.com',
    license='BSD',
    description='todoist-python - The official Todoist Python API library',
    long_description = read('README.md'),
    install_requires=[
        'requests',
    ],
    # see here for complete list of classifiers
    # http://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=(
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Programming Language :: Python',
    ),
)

Prompt:
Update the PyPI version to 7.0.14.

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

def read(fname):
    try:
        return open(os.path.join(os.path.dirname(__file__), fname)).read()
    except:
        return ''

setup(
    name='todoist-python',
    version='7.0.13',
    packages=['todoist', 'todoist.managers'],
    author='Doist Team',
    author_email='info@todoist.com',
    license='BSD',
    description='todoist-python - The official Todoist Python API library',
    long_description = read('README.md'),
    install_requires=[
        'requests',
    ],
    # see here for complete list of classifiers
    # http://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=(
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Programming Language :: Python',
    ),
)


def invokeMenuItem(menu, item):
    menuObject = waitForObjectItem("{type='QMenuBar' visible='true'}", menu)
    activateItem(menuObject)
    activateItem(waitForObjectItem(menuObject, item))

def openQmakeProject(projectPath):
    invokeMenuItem("File", "Open File or Project...")
    waitForObject("{name='QFileDialog' type='QFileDialog' visible='1' windowTitle='Open File'}")
    type(findObject("{name='fileNameEdit' type='QLineEdit'}"), projectPath)
    clickButton(findObject("{text='Open' type='QPushButton'}"))
    waitForObject("{type='Qt4ProjectManager::Internal::ProjectLoadWizard' visible='1' windowTitle='Project Setup'}")
    selectFromCombo(":scrollArea.Create Build Configurations:_QComboBox", "For Each Qt Version One Debug And One Release")
    clickButton(findObject("{text='Finish' type='QPushButton'}"))

def openCmakeProject(projectPath):
    invokeMenuItem("File", "Open File or Project...")
    waitForObject("{name='QFileDialog' type='QFileDialog' visible='1' windowTitle='Open File'}")
    type(findObject("{name='fileNameEdit' type='QLineEdit'}"), projectPath)
    clickButton(findObject("{text='Open' type='QPushButton'}"))
    clickButton(waitForObject(":CMake Wizard.Next_QPushButton", 20000))
    clickButton(waitForObject(":CMake Wizard.Run CMake_QPushButton", 20000))
    clickButton(waitForObject(":CMake Wizard.Finish_QPushButton", 60000))

Response:
<REPLACE_OLD> "per <REPLACE_NEW> "For Each <REPLACE_END> <REPLACE_OLD> a <REPLACE_NEW> One <REPLACE_END> <REPLACE_OLD> and <REPLACE_NEW> And One <REPLACE_END> <|endoftext|>
def invokeMenuItem(menu, item):
    menuObject = waitForObjectItem("{type='QMenuBar' visible='true'}", menu)
    activateItem(menuObject)
    activateItem(waitForObjectItem(menuObject, item))

def openQmakeProject(projectPath):
    invokeMenuItem("File", "Open File or Project...")
    waitForObject("{name='QFileDialog' type='QFileDialog' visible='1' windowTitle='Open File'}")
    type(findObject("{name='fileNameEdit' type='QLineEdit'}"), projectPath)
    clickButton(findObject("{text='Open' type='QPushButton'}"))
    waitForObject("{type='Qt4ProjectManager::Internal::ProjectLoadWizard' visible='1' windowTitle='Project Setup'}")
    selectFromCombo(":scrollArea.Create Build Configurations:_QComboBox", "For Each Qt Version One Debug And One Release")
    clickButton(findObject("{text='Finish' type='QPushButton'}"))

def openCmakeProject(projectPath):
    invokeMenuItem("File", "Open File or Project...")
    waitForObject("{name='QFileDialog' type='QFileDialog' visible='1' windowTitle='Open File'}")
    type(findObject("{name='fileNameEdit' type='QLineEdit'}"), projectPath)
    clickButton(findObject("{text='Open' type='QPushButton'}"))
    clickButton(waitForObject(":CMake Wizard.Next_QPushButton", 20000))
    clickButton(waitForObject(":CMake Wizard.Run CMake_QPushButton", 20000))
    clickButton(waitForObject(":CMake Wizard.Finish_QPushButton", 60000))

Prompt:
Fix openQmakeProject to match new combo value.

Change-Id: Ice0050bf1bb7af59eb57c1e9218d96b3114f4c08
Reviewed-on: http://codereview.qt.nokia.com/4129
Reviewed-by: Qt Sanity Bot <5581206bb7e0307f0d99eb71898ae6b694149ca5@ovi.com>
Reviewed-by: Christian Stenger <accbb51712d7b9c4fb108439d01e716148e5f9e6@nokia.com>

def invokeMenuItem(menu, item):
    menuObject = waitForObjectItem("{type='QMenuBar' visible='true'}", menu)
    activateItem(menuObject)
    activateItem(waitForObjectItem(menuObject, item))

def openQmakeProject(projectPath):
    invokeMenuItem("File", "Open File or Project...")
    waitForObject("{name='QFileDialog' type='QFileDialog' visible='1' windowTitle='Open File'}")
    type(findObject("{name='fileNameEdit' type='QLineEdit'}"), projectPath)
    clickButton(findObject("{text='Open' type='QPushButton'}"))
    waitForObject("{type='Qt4ProjectManager::Internal::ProjectLoadWizard' visible='1' windowTitle='Project Setup'}")
    selectFromCombo(":scrollArea.Create Build Configurations:_QComboBox", "per Qt Version a Debug and Release")
    clickButton(findObject("{text='Finish' type='QPushButton'}"))

def openCmakeProject(projectPath):
    invokeMenuItem("File", "Open File or Project...")
    waitForObject("{name='QFileDialog' type='QFileDialog' visible='1' windowTitle='Open File'}")
    type(findObject("{name='fileNameEdit' type='QLineEdit'}"), projectPath)
    clickButton(findObject("{text='Open' type='QPushButton'}"))
    clickButton(waitForObject(":CMake Wizard.Next_QPushButton", 20000))
    clickButton(waitForObject(":CMake Wizard.Run CMake_QPushButton", 20000))
    clickButton(waitForObject(":CMake Wizard.Finish_QPushButton", 60000))


from django.conf.urls.defaults import *
from util import redirect

urlpatterns = patterns('',

    redirect(r'^b2g', 'firefoxos.firefoxos'),
    redirect(r'^b2g/faq', 'firefoxos.firefoxos'),
    redirect(r'^b2g/about', 'firefoxos.firefoxos'),

    )

Fix view name for b2g redirects

Response:
<REPLACE_OLD> 'firefoxos'),
 <REPLACE_NEW> 'firefoxos.firefoxos'),
 <REPLACE_END> <REPLACE_OLD> 'firefoxos'),
 <REPLACE_NEW> 'firefoxos.firefoxos'),
 <REPLACE_END> <REPLACE_OLD> 'firefoxos'),

 <REPLACE_NEW> 'firefoxos.firefoxos'),

 <REPLACE_END> <|endoftext|> from django.conf.urls.defaults import *
from util import redirect

urlpatterns = patterns('',

    redirect(r'^b2g', 'firefoxos.firefoxos'),
    redirect(r'^b2g/faq', 'firefoxos.firefoxos'),
    redirect(r'^b2g/about', 'firefoxos.firefoxos'),

    )

Prompt:
Fix view name for b2g redirects

bug 792482

from django.conf.urls.defaults import *
from util import redirect

urlpatterns = patterns('',

    redirect(r'^b2g', 'firefoxos'),
    redirect(r'^b2g/faq', 'firefoxos'),
    redirect(r'^b2g/about', 'firefoxos'),

    )


"""Create KAF file based on FoLiA file
Usage: python kaf2folia.py <file in>
"""
from pynlpl.formats import folia
from lxml import etree

# Load document
doc = folia.Document(file='medea-folia-no_events.xml')

# output document
root = etree.Element('KAF')
kaf_document = etree.ElementTree(root)
text = etree.SubElement(root, 'text')

# words
for paragraph in doc.paragraphs():
    for sentence in paragraph.sentences():
        for word in sentence.words():
            w = etree.SubElement(text, 'wf', wid=word.id, sent=sentence.id,
                                 para=paragraph.id)
            w.text = unicode(word)

print etree.tostring(kaf_document, pretty_print=True)

Add script to transform folia into kaf

Add script to transform folia into kaf

Added the first version of the script to transform folia xml into kaf.
The script is not finished, because it is still unknown what the folia
files will exactly look like.

Response:
<INSERT> """Create KAF file based on FoLiA file
Usage: python kaf2folia.py <file in>
"""
from pynlpl.formats import folia
from lxml import etree

# Load document
doc = folia.Document(file='medea-folia-no_events.xml')

# output document
root = etree.Element('KAF')
kaf_document = etree.ElementTree(root)
text = etree.SubElement(root, 'text')

# words
for paragraph in doc.paragraphs():
 <INSERT_END> <INSERT>   for sentence in paragraph.sentences():
        for word in sentence.words():
            w = etree.SubElement(text, 'wf', wid=word.id, sent=sentence.id,
                                 para=paragraph.id)
            w.text = unicode(word)

print etree.tostring(kaf_document, pretty_print=True)
 <INSERT_END> <|endoftext|> """Create KAF file based on FoLiA file
Usage: python kaf2folia.py <file in>
"""
from pynlpl.formats import folia
from lxml import etree

# Load document
doc = folia.Document(file='medea-folia-no_events.xml')

# output document
root = etree.Element('KAF')
kaf_document = etree.ElementTree(root)
text = etree.SubElement(root, 'text')

# words
for paragraph in doc.paragraphs():
    for sentence in paragraph.sentences():
        for word in sentence.words():
            w = etree.SubElement(text, 'wf', wid=word.id, sent=sentence.id,
                                 para=paragraph.id)
            w.text = unicode(word)

print etree.tostring(kaf_document, pretty_print=True)

Prompt:
Add script to transform folia into kaf

Added the first version of the script to transform folia xml into kaf.
The script is not finished, because it is still unknown what the folia
files will exactly look like.


# Overwrite behavior of sympy objects to make more sense for this project.
import symfit.core.operators

# Expose useful objects.
from symfit.core.fit import (
    Fit, Model, ODEModel, ModelError, CallableModel,
    CallableNumericalModel, GradientModel
)
from symfit.core.fit_results import FitResults
from symfit.core.argument import Variable, Parameter
from symfit.core.support import variables, parameters, D

# Expose the sympy API
from sympy import *

Remove Constraint objects from the API

Remove Constraint objects from the API

Response:
<DELETE> Constraint, <DELETE_END> <|endoftext|> # Overwrite behavior of sympy objects to make more sense for this project.
import symfit.core.operators

# Expose useful objects.
from symfit.core.fit import (
    Fit, Model, ODEModel, ModelError, CallableModel,
    CallableNumericalModel, GradientModel
)
from symfit.core.fit_results import FitResults
from symfit.core.argument import Variable, Parameter
from symfit.core.support import variables, parameters, D

# Expose the sympy API
from sympy import *

Prompt:
Remove Constraint objects from the API

# Overwrite behavior of sympy objects to make more sense for this project.
import symfit.core.operators

# Expose useful objects.
from symfit.core.fit import (
    Fit, Model, Constraint, ODEModel, ModelError, CallableModel,
    CallableNumericalModel, GradientModel
)
from symfit.core.fit_results import FitResults
from symfit.core.argument import Variable, Parameter
from symfit.core.support import variables, parameters, D

# Expose the sympy API
from sympy import *


from pythonforandroid.recipe import CompiledComponentsPythonRecipe, Recipe

class CryptographyRecipe(CompiledComponentsPythonRecipe):
    name = 'cryptography'
    version = '2.4.2'
    url = 'https://github.com/pyca/cryptography/archive/{version}.tar.gz'
    depends = ['openssl', 'idna', 'asn1crypto', 'six', 'setuptools',
               'enum34', 'ipaddress', 'cffi']
    call_hostpython_via_targetpython = False

    def get_recipe_env(self, arch):
        env = super(CryptographyRecipe, self).get_recipe_env(arch)

        openssl_recipe = Recipe.get_recipe('openssl', self.ctx)
        env['CFLAGS'] += openssl_recipe.include_flags(arch)
        env['LDFLAGS'] += openssl_recipe.link_dirs_flags(arch)
        env['LIBS'] = openssl_recipe.link_libs_flags()

        return env

recipe = CryptographyRecipe()

Response:
<REPLACE_OLD> openssl_recipe.link_flags(arch)

 <REPLACE_NEW> openssl_recipe.link_dirs_flags(arch)
        env['LIBS'] = openssl_recipe.link_libs_flags()

 <REPLACE_END> <|endoftext|> from pythonforandroid.recipe import CompiledComponentsPythonRecipe, Recipe

class CryptographyRecipe(CompiledComponentsPythonRecipe):
    name = 'cryptography'
    version = '2.4.2'
    url = 'https://github.com/pyca/cryptography/archive/{version}.tar.gz'
    depends = ['openssl', 'idna', 'asn1crypto', 'six', 'setuptools',
               'enum34', 'ipaddress', 'cffi']
    call_hostpython_via_targetpython = False

    def get_recipe_env(self, arch):
        env = super(CryptographyRecipe, self).get_recipe_env(arch)

        openssl_recipe = Recipe.get_recipe('openssl', self.ctx)
        env['CFLAGS'] += openssl_recipe.include_flags(arch)
        env['LDFLAGS'] += openssl_recipe.link_dirs_flags(arch)
        env['LIBS'] = openssl_recipe.link_libs_flags()

        return env

recipe = CryptographyRecipe()

Prompt:
Move libraries from LDFLAGS to LIBS for cryptography recipe

Because this is how you are supposed to do it, you must use LDFLAGS for linker flags and LDLIBS (or the equivalent LOADLIBES) for the libraries

from pythonforandroid.recipe import CompiledComponentsPythonRecipe, Recipe

class CryptographyRecipe(CompiledComponentsPythonRecipe):
    name = 'cryptography'
    version = '2.4.2'
    url = 'https://github.com/pyca/cryptography/archive/{version}.tar.gz'
    depends = ['openssl', 'idna', 'asn1crypto', 'six', 'setuptools',
               'enum34', 'ipaddress', 'cffi']
    call_hostpython_via_targetpython = False

    def get_recipe_env(self, arch):
        env = super(CryptographyRecipe, self).get_recipe_env(arch)

        openssl_recipe = Recipe.get_recipe('openssl', self.ctx)
        env['CFLAGS'] += openssl_recipe.include_flags(arch)
        env['LDFLAGS'] += openssl_recipe.link_flags(arch)

        return env

recipe = CryptographyRecipe()


# Copyright (c) 2013 Mirantis Inc.
#
# 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.

from oslo_serialization import jsonutils
import six

from blazar import context
from blazar import exceptions

def ctx_from_headers(headers):
    try:
        service_catalog = jsonutils.loads(headers['X-Service-Catalog'])
    except KeyError:
        raise exceptions.ServiceCatalogNotFound()
    except TypeError:
        raise exceptions.WrongFormat()

    return context.BlazarContext(
        user_id=headers['X-User-Id'],
        project_id=headers['X-Project-Id'],
        auth_token=headers['X-Auth-Token'],
        service_catalog=service_catalog,
        user_name=headers['X-User-Name'],
        project_name=headers['X-Project-Name'],
        roles=list(map(six.text_type.strip, headers['X-Roles'].split(','))),
    )

Fix map issues with Python3

Response:
<REPLACE_OLD> roles=map(six.text_type.strip, headers['X-Roles'].split(',')),
 <REPLACE_NEW> roles=list(map(six.text_type.strip, headers['X-Roles'].split(','))),
 <REPLACE_END> <|endoftext|> # Copyright (c) 2013 Mirantis Inc.
#
# 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.

from oslo_serialization import jsonutils
import six

from blazar import context
from blazar import exceptions

def ctx_from_headers(headers):
    try:
        service_catalog = jsonutils.loads(headers['X-Service-Catalog'])
    except KeyError:
        raise exceptions.ServiceCatalogNotFound()
    except TypeError:
        raise exceptions.WrongFormat()

    return context.BlazarContext(
        user_id=headers['X-User-Id'],
        project_id=headers['X-Project-Id'],
        auth_token=headers['X-Auth-Token'],
        service_catalog=service_catalog,
        user_name=headers['X-User-Name'],
        project_name=headers['X-Project-Name'],
        roles=list(map(six.text_type.strip, headers['X-Roles'].split(','))),
    )

Prompt:
Fix map issues with Python3

Partially implements: blueprint python-3

Change-Id: Ia7dfc2a28c311a378ca5ada477d18a5b741782b2

# Copyright (c) 2013 Mirantis Inc.
#
# 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.

from oslo_serialization import jsonutils
import six

from blazar import context
from blazar import exceptions

def ctx_from_headers(headers):
    try:
        service_catalog = jsonutils.loads(headers['X-Service-Catalog'])
    except KeyError:
        raise exceptions.ServiceCatalogNotFound()
    except TypeError:
        raise exceptions.WrongFormat()

    return context.BlazarContext(
        user_id=headers['X-User-Id'],
        project_id=headers['X-Project-Id'],
        auth_token=headers['X-Auth-Token'],
        service_catalog=service_catalog,
        user_name=headers['X-User-Name'],
        project_name=headers['X-Project-Name'],
        roles=map(six.text_type.strip, headers['X-Roles'].split(',')),
    )


import unittest
from framework.routing import Rule, json_renderer

class RuleTestCase(unittest.TestCase):

    def _make_rule(self, **kwargs):
        def vf():
            return {}

        return Rule(
            kwargs.get('routes', ['/', ]),
            kwargs.get('methods', ['GET', ]),
            kwargs.get('view_func', vf),
            kwargs.get('render_func', json_renderer),
            kwargs.get('view_kwargs'),
        )

    def test_rule_single_route(self):
        r = self._make_rule(routes='/')
        self.assertEqual(r.routes, ['/', ])

    def test_rule_single_method(self):
        r = self._make_rule(methods='GET')
        self.assertEqual(r.methods, ['GET', ])

    def test_rule_lambda_view(self):
        r = self._make_rule(view_func=lambda: '')
        self.assertTrue(callable(r.view_func))

Fix RuleTestCase -> tests passing

Fix RuleTestCase -> tests passing

Response:
<REPLACE_OLD> Rule

class <REPLACE_NEW> Rule, json_renderer

class <REPLACE_END> <REPLACE_OLD> kwargs.get('render_func'),
 <REPLACE_NEW> kwargs.get('render_func', json_renderer),
 <REPLACE_END> <REPLACE_OLD> self.assertTrue(callable(r.view_func)) <REPLACE_NEW> self.assertTrue(callable(r.view_func))
 <REPLACE_END> <|endoftext|> import unittest
from framework.routing import Rule, json_renderer

class RuleTestCase(unittest.TestCase):

    def _make_rule(self, **kwargs):
        def vf():
            return {}

        return Rule(
            kwargs.get('routes', ['/', ]),
            kwargs.get('methods', ['GET', ]),
            kwargs.get('view_func', vf),
            kwargs.get('render_func', json_renderer),
            kwargs.get('view_kwargs'),
        )

    def test_rule_single_route(self):
        r = self._make_rule(routes='/')
        self.assertEqual(r.routes, ['/', ])

    def test_rule_single_method(self):
        r = self._make_rule(methods='GET')
        self.assertEqual(r.methods, ['GET', ])

    def test_rule_lambda_view(self):
        r = self._make_rule(view_func=lambda: '')
        self.assertTrue(callable(r.view_func))

Prompt:
Fix RuleTestCase -> tests passing

import unittest
from framework.routing import Rule

class RuleTestCase(unittest.TestCase):

    def _make_rule(self, **kwargs):
        def vf():
            return {}

        return Rule(
            kwargs.get('routes', ['/', ]),
            kwargs.get('methods', ['GET', ]),
            kwargs.get('view_func', vf),
            kwargs.get('render_func'),
            kwargs.get('view_kwargs'),
        )

    def test_rule_single_route(self):
        r = self._make_rule(routes='/')
        self.assertEqual(r.routes, ['/', ])

    def test_rule_single_method(self):
        r = self._make_rule(methods='GET')
        self.assertEqual(r.methods, ['GET', ])

    def test_rule_lambda_view(self):
        r = self._make_rule(view_func=lambda: '')
        self.assertTrue(callable(r.view_func))


from distutils.core import Extension, setup

from Cython.Build import cythonize

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

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

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

    cmdclass = {}

setup(
    name='mathix',

    author='Peith Vergil',

    version='0.1',

    cmdclass=cmdclass,

    packages=[
        'mathix',
    ],

    keywords='useless simple math library',

    description='A useless simple math library.',

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

    ext_modules=cythonize(extensions)
)

Response:
<REPLACE_OLD> cythonize

extensions <REPLACE_NEW> cythonize

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

if use_cython:
    extensions <REPLACE_END> <REPLACE_OLD> Extension('*', ['mathix/*.pyx']),
]

setup(
 <REPLACE_NEW>     Extension('mathix.vector', ['mathix/vector.pyx']),
    ]

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

    cmdclass = {}

setup(
 <REPLACE_END> <INSERT> cmdclass=cmdclass,

    packages=[
        'mathix',
    ],

    keywords='useless simple math library',

    description='A useless simple math library.',

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

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

from Cython.Build import cythonize

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

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

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

    cmdclass = {}

setup(
    name='mathix',

    author='Peith Vergil',

    version='0.1',

    cmdclass=cmdclass,

    packages=[
        'mathix',
    ],

    keywords='useless simple math library',

    description='A useless simple math library.',

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

    ext_modules=cythonize(extensions)
)

Prompt:
Add more classifiers. Check if Cython compilation is available or not.

from distutils.core import Extension, setup

from Cython.Build import cythonize

extensions = [
    Extension('*', ['mathix/*.pyx']),
]

setup(
    name='mathix',

    author='Peith Vergil',

    version='0.1',

    ext_modules=cythonize(extensions)
)


__all__ = ('to_bool', 'ConfigPropertyList')

from kivy.properties import ConfigParserProperty
from re import compile, split

to_list_pat = compile('(?:, *)?\\n?')

def to_bool(val):
    '''
    Takes anything and converts it to a bool type.
    '''
    if val == 'False':
        return False
    return not not val

def ConfigPropertyList(val, section, key, config, val_type, inner_list=False,
                       **kwargs):
    ''' Accepts either a list of a string. Nothing else.
    '''
    def to_list(val):
        if isinstance(val, list):
            vals = list(val)
        else:
            vals = split(to_list_pat, val.strip(' []()'))
        for i, v in enumerate(vals):
            vals[i] = val_type(v)
        return vals

    def to_2d_list(val):
        if isinstance(val, list):
            vals = list(val)
        else:
            vals = [split(to_list_pat, line.strip(' []()'))
                    for line in val.strip(' []()').splitlines()]
        for i, line in enumerate(vals):
            for j, v in enumerate(line):
                vals[i][j] = val_type(v)
        return vals

    if not isinstance(val, list):
        val = [[val]] if inner_list else [val]
    v_type = to_2d_list if inner_list else to_list
    return ConfigParserProperty(val, section, key, config, val_type=v_type,
                                **kwargs)

Add 2d list to ConfigProperty.

Add 2d list to ConfigProperty.

Response:
<REPLACE_OLD> split
from functools import partial

to_list_pat = compile(', *')

def <REPLACE_NEW> split

to_list_pat = compile('(?:, *)?\\n?')

def <REPLACE_END> <INSERT> inner_list=False,
                       <INSERT_END> <INSERT>    ''' Accepts either a list of a string. Nothing else.
    '''
 <INSERT_END> <REPLACE_OLD> val
 <REPLACE_NEW> list(val)
 <REPLACE_END> <INSERT> def to_2d_list(val):
        if isinstance(val, list):
            vals = list(val)
        else:
            vals = [split(to_list_pat, line.strip(' []()'))
                    for line in val.strip(' []()').splitlines()]
        for i, line in enumerate(vals):
            for j, v in enumerate(line):
                vals[i][j] = val_type(v)
        return vals

    <INSERT_END> <INSERT> [[val]] if inner_list else <INSERT_END> <INSERT>    v_type = to_2d_list if inner_list else to_list
 <INSERT_END> <REPLACE_OLD> val_type=to_list,
 <REPLACE_NEW> val_type=v_type,
 <REPLACE_END> <|endoftext|>
__all__ = ('to_bool', 'ConfigPropertyList')

from kivy.properties import ConfigParserProperty
from re import compile, split

to_list_pat = compile('(?:, *)?\\n?')

def to_bool(val):
    '''
    Takes anything and converts it to a bool type.
    '''
    if val == 'False':
        return False
    return not not val

def ConfigPropertyList(val, section, key, config, val_type, inner_list=False,
                       **kwargs):
    ''' Accepts either a list of a string. Nothing else.
    '''
    def to_list(val):
        if isinstance(val, list):
            vals = list(val)
        else:
            vals = split(to_list_pat, val.strip(' []()'))
        for i, v in enumerate(vals):
            vals[i] = val_type(v)
        return vals

    def to_2d_list(val):
        if isinstance(val, list):
            vals = list(val)
        else:
            vals = [split(to_list_pat, line.strip(' []()'))
                    for line in val.strip(' []()').splitlines()]
        for i, line in enumerate(vals):
            for j, v in enumerate(line):
                vals[i][j] = val_type(v)
        return vals

    if not isinstance(val, list):
        val = [[val]] if inner_list else [val]
    v_type = to_2d_list if inner_list else to_list
    return ConfigParserProperty(val, section, key, config, val_type=v_type,
                                **kwargs)

Prompt:
Add 2d list to ConfigProperty.

__all__ = ('to_bool', 'ConfigPropertyList')

from kivy.properties import ConfigParserProperty
from re import compile, split
from functools import partial

to_list_pat = compile(', *')

def to_bool(val):
    '''
    Takes anything and converts it to a bool type.
    '''
    if val == 'False':
        return False
    return not not val

def ConfigPropertyList(val, section, key, config, val_type, **kwargs):
    def to_list(val):
        if isinstance(val, list):
            vals = val
        else:
            vals = split(to_list_pat, val.strip(' []()'))
        for i, v in enumerate(vals):
            vals[i] = val_type(v)
        return vals

    if not isinstance(val, list):
        val = [val]
    return ConfigParserProperty(val, section, key, config, val_type=to_list,
                                **kwargs)


# -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-07-26 18:14
from __future__ import unicode_literals

from django.db import migrations

SEAT_TYPES = ('audit', 'verified',)
PROGRAM_TYPES = ('MicroBachelors',)

def add_program_types(apps, schema_editor):  # pylint: disable=unused-argument
    SeatType = apps.get_model('course_metadata', 'SeatType')
    ProgramType = apps.get_model('course_metadata', 'ProgramType')

    filtered_seat_types = SeatType.objects.filter(slug__in=SEAT_TYPES)

    for name in PROGRAM_TYPES:
        program_type, __ = ProgramType.objects.update_or_create(name=name)
        program_type.applicable_seat_types.clear()
        program_type.applicable_seat_types.add(*filtered_seat_types)
        program_type.save()

def drop_program_types(apps, schema_editor):  # pylint: disable=unused-argument
    ProgramType = apps.get_model('course_metadata', 'ProgramType')
    ProgramType.objects.filter(name__in=PROGRAM_TYPES).delete()

class Migration(migrations.Migration):

    dependencies = [
        ('course_metadata', '0190_remove_entitlement_expires'),
    ]

    operations = [
        migrations.RunPython(
            code=add_program_types,
            reverse_code=drop_program_types,
        ),
    ]

MICROB-3: Add MicroBachelors program_type
Co-authored-by: Lise <albemarle>

Response:
<INSERT> # -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-07-26 18:14
from __future__ import unicode_literals

from django.db import migrations

SEAT_TYPES = ('audit', 'verified',)
PROGRAM_TYPES = ('MicroBachelors',)

def add_program_types(apps, schema_editor): <INSERT_END> <INSERT> # pylint: disable=unused-argument
    SeatType = apps.get_model('course_metadata', 'SeatType')
    ProgramType = apps.get_model('course_metadata', 'ProgramType')

    filtered_seat_types = SeatType.objects.filter(slug__in=SEAT_TYPES)

    for name in PROGRAM_TYPES:
        program_type, __ = ProgramType.objects.update_or_create(name=name)
        program_type.applicable_seat_types.clear()
        program_type.applicable_seat_types.add(*filtered_seat_types)
        program_type.save()

def drop_program_types(apps, schema_editor):  # pylint: disable=unused-argument
    ProgramType = apps.get_model('course_metadata', 'ProgramType')
    ProgramType.objects.filter(name__in=PROGRAM_TYPES).delete()

class Migration(migrations.Migration):

    dependencies = [
        ('course_metadata', '0190_remove_entitlement_expires'),
    ]

    operations = [
        migrations.RunPython(
            code=add_program_types,
            reverse_code=drop_program_types,
        ),
    ]
 <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-07-26 18:14
from __future__ import unicode_literals

from django.db import migrations

SEAT_TYPES = ('audit', 'verified',)
PROGRAM_TYPES = ('MicroBachelors',)

def add_program_types(apps, schema_editor):  # pylint: disable=unused-argument
    SeatType = apps.get_model('course_metadata', 'SeatType')
    ProgramType = apps.get_model('course_metadata', 'ProgramType')

    filtered_seat_types = SeatType.objects.filter(slug__in=SEAT_TYPES)

    for name in PROGRAM_TYPES:
        program_type, __ = ProgramType.objects.update_or_create(name=name)
        program_type.applicable_seat_types.clear()
        program_type.applicable_seat_types.add(*filtered_seat_types)
        program_type.save()

def drop_program_types(apps, schema_editor):  # pylint: disable=unused-argument
    ProgramType = apps.get_model('course_metadata', 'ProgramType')
    ProgramType.objects.filter(name__in=PROGRAM_TYPES).delete()

class Migration(migrations.Migration):

    dependencies = [
        ('course_metadata', '0190_remove_entitlement_expires'),
    ]

    operations = [
        migrations.RunPython(
            code=add_program_types,
            reverse_code=drop_program_types,
        ),
    ]

Prompt:
MICROB-3: Add MicroBachelors program_type
Co-authored-by: Lise <albemarle>


#!/usr/bin/env python

import os
import sys
import time
import getpass
import datetime

from common.appenginepatch.aecmd import setup_env
setup_env()

import ADNS
from adns import rr

from google.appengine.ext import db
from google.appengine.ext.remote_api import remote_api_stub
from google.appengine.api.datastore_errors import Timeout

from domains.models import Domain, Whois

BATCH_SIZE = 400
MAX_ATTEMPTS = 5

def auth_func():
    return open('.passwd').read().split(':')

def delete_batch(objects):
    if not objects:
        return
    for attempt in range(MAX_ATTEMPTS):
        if attempt:
            print "Attempt %d of %d will start in %d seconds." % (
                attempt + 1, MAX_ATTEMPTS, attempt)
            time.sleep(attempt)
        print "Deleting %d objects (%s to %s):" % (
            len(objects), objects[0].name(), objects[-1].name())
        try:
            db.delete(objects)
            break
        except Timeout:
            print "*** Timeout ***"
            if attempt + 1 == MAX_ATTEMPTS:
                sys.exit(1)
    del objects[:]

def main():
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option('--server', metavar='<hostname>',
                      default='scoretool.appspot.com',
                      help="connect to a different server")
    (options, args) = parser.parse_args()
    remote_api_stub.ConfigureRemoteDatastore(
        'scoretool', '/remote_api', auth_func, options.server)
    while True:
        whois_keys = Whois.all(keys_only=True).fetch(BATCH_SIZE)
        delete_batch(whois_keys)

if __name__ == '__main__':
    main()

Delete obsolete Whois model from the datastore.

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

import os
import sys
import time
import getpass
import datetime

from common.appenginepatch.aecmd import setup_env
setup_env()

import ADNS
from adns import rr

from google.appengine.ext import db
from google.appengine.ext.remote_api import remote_api_stub
from google.appengine.api.datastore_errors import Timeout

from domains.models import Domain, Whois

BATCH_SIZE = 400
MAX_ATTEMPTS = 5

def auth_func():
    return open('.passwd').read().split(':')

def delete_batch(objects):
    if not objects:
        return
    for attempt in range(MAX_ATTEMPTS):
        if attempt:
            print "Attempt %d of %d will start in %d seconds." % (
                attempt + 1, MAX_ATTEMPTS, attempt)
            time.sleep(attempt)
        print "Deleting %d objects (%s to %s):" % (
            len(objects), objects[0].name(), objects[-1].name())
        try:
            db.delete(objects)
            break
        except Timeout:
            print "*** Timeout ***"
            if attempt + 1 == MAX_ATTEMPTS:
                sys.exit(1)
    del objects[:]

def main():
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option('--server', metavar='<hostname>',
                      default='scoretool.appspot.com',
                      help="connect to a different server")
    (options, args) = parser.parse_args()
    remote_api_stub.ConfigureRemoteDatastore(
        'scoretool', '/remote_api', auth_func, options.server)
    while True:
        whois_keys = Whois.all(keys_only=True).fetch(BATCH_SIZE)
        delete_batch(whois_keys)

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

import os
import sys
import time
import getpass
import datetime

from common.appenginepatch.aecmd import setup_env
setup_env()

import ADNS
from adns import rr

from google.appengine.ext import db
from google.appengine.ext.remote_api import remote_api_stub
from google.appengine.api.datastore_errors import Timeout

from domains.models import Domain, Whois

BATCH_SIZE = 400
MAX_ATTEMPTS = 5

def auth_func():
    return open('.passwd').read().split(':')

def delete_batch(objects):
    if not objects:
        return
    for attempt in range(MAX_ATTEMPTS):
        if attempt:
            print "Attempt %d of %d will start in %d seconds." % (
                attempt + 1, MAX_ATTEMPTS, attempt)
            time.sleep(attempt)
        print "Deleting %d objects (%s to %s):" % (
            len(objects), objects[0].name(), objects[-1].name())
        try:
            db.delete(objects)
            break
        except Timeout:
            print "*** Timeout ***"
            if attempt + 1 == MAX_ATTEMPTS:
                sys.exit(1)
    del objects[:]

def main():
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option('--server', metavar='<hostname>',
                      default='scoretool.appspot.com',
                      help="connect to a different server")
    (options, args) = parser.parse_args()
    remote_api_stub.ConfigureRemoteDatastore(
        'scoretool', '/remote_api', auth_func, options.server)
    while True:
        whois_keys = Whois.all(keys_only=True).fetch(BATCH_SIZE)
        delete_batch(whois_keys)

if __name__ == '__main__':
    main()

Prompt: Delete obsolete Whois model from the datastore.


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

import unittest

import const
import uniformdh

import obfsproxy.network.buffer as obfs_buf

class UniformDHTest( unittest.TestCase ):

    def setUp( self ):
        weAreServer = True
        self.udh = uniformdh.new("A" * const.SHARED_SECRET_LENGTH, weAreServer)

    def test1_createHandshake( self ):
        handshake = self.udh.createHandshake()
        self.failUnless((const.PUBLIC_KEY_LENGTH +
                         const.MARKER_LENGTH +
                         const.HMAC_LENGTH) <= len(handshake) <=
                        (const.MARKER_LENGTH +
                         const.HMAC_LENGTH +
                         const.MAX_PADDING_LENGTH))

    def test2_receivePublicKey( self ):
        buf = obfs_buf.Buffer(self.udh.createHandshake())

        self.failUnless(self.udh.receivePublicKey(buf, lambda x: x) == True)

        publicKey = self.udh.getRemotePublicKey()
        self.failUnless(len(publicKey) == const.PUBLIC_KEY_LENGTH)

    def test3_invalidHMAC( self ):
        # Make the HMAC invalid.
        handshake = self.udh.createHandshake()
        if handshake[-1] != 'a':
            handshake = handshake[:-1] + 'a'
        else:
            handshake = handshake[:-1] + 'b'

        buf = obfs_buf.Buffer(handshake)

        self.failIf(self.udh.receivePublicKey(buf, lambda x: x) == True)

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

Response:
<REPLACE_OLD> const.PUBLIC_KEY_LENGTH)

if <REPLACE_NEW> const.PUBLIC_KEY_LENGTH)

    def test3_invalidHMAC( self ):
        # Make the HMAC invalid.
        handshake = self.udh.createHandshake()
        if handshake[-1] != 'a':
            handshake = handshake[:-1] + 'a'
        else:
            handshake = handshake[:-1] + 'b'

        buf = obfs_buf.Buffer(handshake)

        self.failIf(self.udh.receivePublicKey(buf, lambda x: x) == True)

if <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-

import unittest

import const
import uniformdh

import obfsproxy.network.buffer as obfs_buf

class UniformDHTest( unittest.TestCase ):

    def setUp( self ):
        weAreServer = True
        self.udh = uniformdh.new("A" * const.SHARED_SECRET_LENGTH, weAreServer)

    def test1_createHandshake( self ):
        handshake = self.udh.createHandshake()
        self.failUnless((const.PUBLIC_KEY_LENGTH +
                         const.MARKER_LENGTH +
                         const.HMAC_LENGTH) <= len(handshake) <=
                        (const.MARKER_LENGTH +
                         const.HMAC_LENGTH +
                         const.MAX_PADDING_LENGTH))

    def test2_receivePublicKey( self ):
        buf = obfs_buf.Buffer(self.udh.createHandshake())

        self.failUnless(self.udh.receivePublicKey(buf, lambda x: x) == True)

        publicKey = self.udh.getRemotePublicKey()
        self.failUnless(len(publicKey) == const.PUBLIC_KEY_LENGTH)

    def test3_invalidHMAC( self ):
        # Make the HMAC invalid.
        handshake = self.udh.createHandshake()
        if handshake[-1] != 'a':
            handshake = handshake[:-1] + 'a'
        else:
            handshake = handshake[:-1] + 'b'

        buf = obfs_buf.Buffer(handshake)

        self.failIf(self.udh.receivePublicKey(buf, lambda x: x) == True)

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

Prompt:
Add UniformDH unit test to test for invalid HMACs.

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

import unittest

import const
import uniformdh

import obfsproxy.network.buffer as obfs_buf

class UniformDHTest( unittest.TestCase ):

    def setUp( self ):
        weAreServer = True
        self.udh = uniformdh.new("A" * const.SHARED_SECRET_LENGTH, weAreServer)

    def test1_createHandshake( self ):
        handshake = self.udh.createHandshake()
        self.failUnless((const.PUBLIC_KEY_LENGTH +
                         const.MARKER_LENGTH +
                         const.HMAC_LENGTH) <= len(handshake) <=
                        (const.MARKER_LENGTH +
                         const.HMAC_LENGTH +
                         const.MAX_PADDING_LENGTH))

    def test2_receivePublicKey( self ):
        buf = obfs_buf.Buffer(self.udh.createHandshake())

        self.failUnless(self.udh.receivePublicKey(buf, lambda x: x) == True)

        publicKey = self.udh.getRemotePublicKey()
        self.failUnless(len(publicKey) == const.PUBLIC_KEY_LENGTH)

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


import subprocess
import sys
from distutils.core import setup, Command

class TestCommand(Command):
    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        errno = subprocess.call([sys.executable, 'test_facebook.py'])
        raise SystemExit(errno)

setup(
    name='facebook-ads-api',
    version='0.1.41',
    author='Chee-Hyung Yoon',
    author_email='yoonchee@gmail.com',
    py_modules=['facebook', ],
    url='http://github.com/narrowcast/facebook-ads-api',
    license='LICENSE',
    description='Python client for the Facebook Ads API',
    long_description=open('README.md').read(),
    cmdclass={'test': TestCommand},
)

Response:
<REPLACE_OLD> version='0.1.40',
 <REPLACE_NEW> version='0.1.41',
 <REPLACE_END> <|endoftext|> import subprocess
import sys
from distutils.core import setup, Command

class TestCommand(Command):
    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        errno = subprocess.call([sys.executable, 'test_facebook.py'])
        raise SystemExit(errno)

setup(
    name='facebook-ads-api',
    version='0.1.41',
    author='Chee-Hyung Yoon',
    author_email='yoonchee@gmail.com',
    py_modules=['facebook', ],
    url='http://github.com/narrowcast/facebook-ads-api',
    license='LICENSE',
    description='Python client for the Facebook Ads API',
    long_description=open('README.md').read(),
    cmdclass={'test': TestCommand},
)

Prompt:
Add method for adding users to a custom audience.

import subprocess
import sys
from distutils.core import setup, Command

class TestCommand(Command):
    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        errno = subprocess.call([sys.executable, 'test_facebook.py'])
        raise SystemExit(errno)

setup(
    name='facebook-ads-api',
    version='0.1.40',
    author='Chee-Hyung Yoon',
    author_email='yoonchee@gmail.com',
    py_modules=['facebook', ],
    url='http://github.com/narrowcast/facebook-ads-api',
    license='LICENSE',
    description='Python client for the Facebook Ads API',
    long_description=open('README.md').read(),
    cmdclass={'test': TestCommand},
)


"""
This simulates the mlab-ns lookup request, whose code lives here:

https://code.google.com/p/m-lab/source/browse/server/mlabns/handlers/lookup.py?repo=ns

The difference in this module is that we don't support features which
ooni-support does not use and we augment features which ooni-support
would rely on if mlab-ns were to add those features.

Also, this is a twisted web server rather than appengine.
"""

import json

from twisted.web import resource
from twisted.web.server import NOT_DONE_YET

class LookupSimulatorResource (resource.Resource):
    def __init__(self, db):
        """db is a dict mapping { fqdn -> other_stuff }; inserts come from mlabsim.update."""
        resource.Resource.__init__(self)
        self._db = db

    def render_GET(self, request):
        if request.args['match'] == ['all'] and request.args.get('format', ['json']) == ['json']:
            request.setResponseCode(200, 'ok')
            request.write(json.dumps(self._db.values(), indent=2, sort_keys=True))
            request.finish()
        else:
            request.setResponseCode(400, 'invalid')
            request.finish()
        return NOT_DONE_YET

Response:
<REPLACE_OLD> appengine.
"""

from <REPLACE_NEW> appengine.
"""

import json

from <REPLACE_END> <REPLACE_OLD> # FIXME - db <REPLACE_NEW> """db <REPLACE_END> <REPLACE_OLD> some simple memory structure holding info;
        # the details will solidfy soon.  This resource reads from
        # this structure.

 <REPLACE_NEW> a dict mapping { fqdn -> other_stuff }; inserts come from mlabsim.update."""
 <REPLACE_END> <REPLACE_OLD> # FIXME: This is not implemented yet.
        request.setResponseCode(500, 'NOT IMPLEMENTED')
 <REPLACE_NEW> if request.args['match'] == ['all'] and request.args.get('format', ['json']) == ['json']:
            request.setResponseCode(200, 'ok')
            request.write(json.dumps(self._db.values(), indent=2, sort_keys=True))
            request.finish()
        else:
            request.setResponseCode(400, 'invalid')
     <REPLACE_END> <|endoftext|> """
This simulates the mlab-ns lookup request, whose code lives here:

https://code.google.com/p/m-lab/source/browse/server/mlabns/handlers/lookup.py?repo=ns

The difference in this module is that we don't support features which
ooni-support does not use and we augment features which ooni-support
would rely on if mlab-ns were to add those features.

Also, this is a twisted web server rather than appengine.
"""

import json

from twisted.web import resource
from twisted.web.server import NOT_DONE_YET

class LookupSimulatorResource (resource.Resource):
    def __init__(self, db):
        """db is a dict mapping { fqdn -> other_stuff }; inserts come from mlabsim.update."""
        resource.Resource.__init__(self)
        self._db = db

    def render_GET(self, request):
        if request.args['match'] == ['all'] and request.args.get('format', ['json']) == ['json']:
            request.setResponseCode(200, 'ok')
            request.write(json.dumps(self._db.values(), indent=2, sort_keys=True))
            request.finish()
        else:
            request.setResponseCode(400, 'invalid')
            request.finish()
        return NOT_DONE_YET

Prompt:
Implement the current ``GET /ooni`` api.

"""
This simulates the mlab-ns lookup request, whose code lives here:

https://code.google.com/p/m-lab/source/browse/server/mlabns/handlers/lookup.py?repo=ns

The difference in this module is that we don't support features which
ooni-support does not use and we augment features which ooni-support
would rely on if mlab-ns were to add those features.

Also, this is a twisted web server rather than appengine.
"""

from twisted.web import resource
from twisted.web.server import NOT_DONE_YET

class LookupSimulatorResource (resource.Resource):
    def __init__(self, db):
        # FIXME - db is some simple memory structure holding info;
        # the details will solidfy soon.  This resource reads from
        # this structure.

        resource.Resource.__init__(self)
        self._db = db

    def render_GET(self, request):
        # FIXME: This is not implemented yet.
        request.setResponseCode(500, 'NOT IMPLEMENTED')
        request.finish()
        return NOT_DONE_YET


'''A framework for designing and running experiments in Python using Kivy.
'''

__version__ = '0.1-dev'

from kivy import kivy_home_dir
from os import environ
from os.path import join

if 'MOA_CLOCK' in environ:
    from moa.clock import set_clock
    set_clock(clock='moa')

from moa.logger import Logger

#: moa configuration filename
moa_config_fn = ''

if not environ.get('MOA_DOC_INCLUDE'):
    moa_config_fn = join(kivy_home_dir, 'moa_config.ini')

Logger.info('Moa v%s' % (__version__))

Add config option to start moa clock.

Add config option to start moa clock.

Response:
<REPLACE_OLD> join
from <REPLACE_NEW> join

if 'MOA_CLOCK' in environ:
    from moa.clock import set_clock
    set_clock(clock='moa')

from <REPLACE_END> <|endoftext|> '''A framework for designing and running experiments in Python using Kivy.
'''

__version__ = '0.1-dev'

from kivy import kivy_home_dir
from os import environ
from os.path import join

if 'MOA_CLOCK' in environ:
    from moa.clock import set_clock
    set_clock(clock='moa')

from moa.logger import Logger

#: moa configuration filename
moa_config_fn = ''

if not environ.get('MOA_DOC_INCLUDE'):
    moa_config_fn = join(kivy_home_dir, 'moa_config.ini')

Logger.info('Moa v%s' % (__version__))

Prompt:
Add config option to start moa clock.

'''A framework for designing and running experiments in Python using Kivy.
'''

__version__ = '0.1-dev'

from kivy import kivy_home_dir
from os import environ
from os.path import join
from moa.logger import Logger

#: moa configuration filename
moa_config_fn = ''

if not environ.get('MOA_DOC_INCLUDE'):
    moa_config_fn = join(kivy_home_dir, 'moa_config.ini')

Logger.info('Moa v%s' % (__version__))


import sys
import ssl
import urllib.error
import urllib.request

host = sys.argv[1]
port = sys.argv[2]
cafile = sys.argv[3] if len(sys.argv) > 3 else None

try:
    urllib.request.urlopen("https://" + host + ":" + port, cafile=cafile)
except urllib.error.URLError as exc:
    if not isinstance(exc.reason, ssl.SSLError):
        raise
    print("FAIL")
else:
    print("OK")

Add a Python3 + urllib example

Add a Python3 + urllib example

Response:
<INSERT> import sys
import ssl
import urllib.error
import urllib.request

host = sys.argv[1]
port = sys.argv[2]
cafile = sys.argv[3] if len(sys.argv) > 3 else None

try:
 <INSERT_END> <INSERT>   urllib.request.urlopen("https://" + host + ":" + port, cafile=cafile)
except urllib.error.URLError as exc:
    if not isinstance(exc.reason, ssl.SSLError):
        raise
    print("FAIL")
else:
    print("OK")
 <INSERT_END> <|endoftext|> import sys
import ssl
import urllib.error
import urllib.request

host = sys.argv[1]
port = sys.argv[2]
cafile = sys.argv[3] if len(sys.argv) > 3 else None

try:
    urllib.request.urlopen("https://" + host + ":" + port, cafile=cafile)
except urllib.error.URLError as exc:
    if not isinstance(exc.reason, ssl.SSLError):
        raise
    print("FAIL")
else:
    print("OK")

Prompt: Add a Python3 + urllib example


#! /usr/bin/env python
""" Test suite.
"""
from __future__ import absolute_import
import sys
import unittest

from . import unittest_neos
from . import unittest_sedumi_writer

def main():
    """ The main function.

    Returns:
      True if all tests are successful.
    """
    loader = unittest.TestLoader()
    suite = unittest.TestSuite()

    suite.addTest(loader.loadTestsFromModule(unittest_neos))
    suite.addTest(loader.loadTestsFromModule(unittest_sedumi_writer))

    res = unittest.TextTestRunner(verbosity=2).run(suite)
    return res.wasSuccessful()

if __name__ == "__main__":
    try:
        sys.exit(0 if main() else 1)
    except KeyboardInterrupt:
        print "Test canceled."
        sys.exit(-1)

Response:
<REPLACE_OLD> python
from <REPLACE_NEW> python
""" Test suite.
"""
from <REPLACE_END> <INSERT> sys
import <INSERT_END> <REPLACE_OLD> function.
 <REPLACE_NEW> function.

    Returns:
      True if all tests are successful.
 <REPLACE_END> <REPLACE_OLD> unittest.TextTestRunner(verbosity=2).run(suite)

if <REPLACE_NEW> res = unittest.TextTestRunner(verbosity=2).run(suite)
    return res.wasSuccessful()

if <REPLACE_END> <REPLACE_OLD> main()
 <REPLACE_NEW> sys.exit(0 if main() else 1)
 <REPLACE_END> <INSERT>        sys.exit(-1)
 <INSERT_END> <|endoftext|> #! /usr/bin/env python
""" Test suite.
"""
from __future__ import absolute_import
import sys
import unittest

from . import unittest_neos
from . import unittest_sedumi_writer

def main():
    """ The main function.

    Returns:
      True if all tests are successful.
    """
    loader = unittest.TestLoader()
    suite = unittest.TestSuite()

    suite.addTest(loader.loadTestsFromModule(unittest_neos))
    suite.addTest(loader.loadTestsFromModule(unittest_sedumi_writer))

    res = unittest.TextTestRunner(verbosity=2).run(suite)
    return res.wasSuccessful()

if __name__ == "__main__":
    try:
        sys.exit(0 if main() else 1)
    except KeyboardInterrupt:
        print "Test canceled."
        sys.exit(-1)

Prompt:
Fix a bug to return error status code when tests are failed.

#! /usr/bin/env python
from __future__ import absolute_import
import unittest

from . import unittest_neos
from . import unittest_sedumi_writer

def main():
    """ The main function.
    """
    loader = unittest.TestLoader()
    suite = unittest.TestSuite()

    suite.addTest(loader.loadTestsFromModule(unittest_neos))
    suite.addTest(loader.loadTestsFromModule(unittest_sedumi_writer))

    unittest.TextTestRunner(verbosity=2).run(suite)

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print "Test canceled."


# all the values are in seconds
ENDPOINT_UP_TIMEOUT = 60 * 20
MADCORE_UP_TIMEOUT = 60 * 60
DNS_RESOLVE_TIMEOUT = 60 * 30
DNS_UPDATE_TIMEOUT = 60 * 10
DOMAIN_HAS_SSL_CERTIFICATE_TIMEOUT = 60

Increase timeout for endpoint up

Increase timeout  for endpoint up

Response:
<REPLACE_OLD> 10
MADCORE_UP_TIMEOUT <REPLACE_NEW> 20
MADCORE_UP_TIMEOUT <REPLACE_END> <|endoftext|> # all the values are in seconds
ENDPOINT_UP_TIMEOUT = 60 * 20
MADCORE_UP_TIMEOUT = 60 * 60
DNS_RESOLVE_TIMEOUT = 60 * 30
DNS_UPDATE_TIMEOUT = 60 * 10
DOMAIN_HAS_SSL_CERTIFICATE_TIMEOUT = 60

Prompt:
Increase timeout  for endpoint up

# all the values are in seconds
ENDPOINT_UP_TIMEOUT = 60 * 10
MADCORE_UP_TIMEOUT = 60 * 60
DNS_RESOLVE_TIMEOUT = 60 * 30
DNS_UPDATE_TIMEOUT = 60 * 10
DOMAIN_HAS_SSL_CERTIFICATE_TIMEOUT = 60


import unittest

from LinkMeBot.utils import get_text_from_markdown, human_readable_download_number

class TestUtils(unittest.TestCase):
    def test_get_text_from_markdown(self):
        markdown = '**test** [^this](https://google.com) ~~is~~ _a_ test! https://google.com'
        text = 'test this is a test!'
        self.assertEqual(get_text_from_markdown(markdown), text)

        # make sure quoted text is discarded
        markdown = '''test
> this is a test

hello world
        '''
        text = 'test\n\nhello world'
        self.assertEqual(get_text_from_markdown(markdown), text)

    def test_human_readable_download_number(self):
        self.assertEqual(human_readable_download_number('12'), '12')
        self.assertEqual(human_readable_download_number('12000'), '12 thousand')
        self.assertEqual(human_readable_download_number('12000000'), '12 million')
        self.assertEqual(human_readable_download_number('12,000,000 - 15,000,000'), '12 million')

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

Fix tests for human readable numbers

Fix tests for human readable numbers

Response:
<REPLACE_OLD> Thousand')
 <REPLACE_NEW> thousand')
 <REPLACE_END> <REPLACE_OLD> Million')
 <REPLACE_NEW> million')
 <REPLACE_END> <REPLACE_OLD> Million') <REPLACE_NEW> million') <REPLACE_END> <|endoftext|> import unittest

from LinkMeBot.utils import get_text_from_markdown, human_readable_download_number

class TestUtils(unittest.TestCase):
    def test_get_text_from_markdown(self):
        markdown = '**test** [^this](https://google.com) ~~is~~ _a_ test! https://google.com'
        text = 'test this is a test!'
        self.assertEqual(get_text_from_markdown(markdown), text)

        # make sure quoted text is discarded
        markdown = '''test
> this is a test

hello world
        '''
        text = 'test\n\nhello world'
        self.assertEqual(get_text_from_markdown(markdown), text)

    def test_human_readable_download_number(self):
        self.assertEqual(human_readable_download_number('12'), '12')
        self.assertEqual(human_readable_download_number('12000'), '12 thousand')
        self.assertEqual(human_readable_download_number('12000000'), '12 million')
        self.assertEqual(human_readable_download_number('12,000,000 - 15,000,000'), '12 million')

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

Prompt:
Fix tests for human readable numbers

import unittest

from LinkMeBot.utils import get_text_from_markdown, human_readable_download_number

class TestUtils(unittest.TestCase):
    def test_get_text_from_markdown(self):
        markdown = '**test** [^this](https://google.com) ~~is~~ _a_ test! https://google.com'
        text = 'test this is a test!'
        self.assertEqual(get_text_from_markdown(markdown), text)

        # make sure quoted text is discarded
        markdown = '''test
> this is a test

hello world
        '''
        text = 'test\n\nhello world'
        self.assertEqual(get_text_from_markdown(markdown), text)

    def test_human_readable_download_number(self):
        self.assertEqual(human_readable_download_number('12'), '12')
        self.assertEqual(human_readable_download_number('12000'), '12 Thousand')
        self.assertEqual(human_readable_download_number('12000000'), '12 Million')
        self.assertEqual(human_readable_download_number('12,000,000 - 15,000,000'), '12 Million')

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


import pyseidon
import sys

def handle_script():
    import runpy
    """
Allow the client to run an arbitrary Python script.

Here's sample usage:

```
def expensive_setup():
  ...

if __name__ == '__main__':
  expensive_setup()

  import pyseidon.handlers
  pyseidon.handlers.handle_script()
```
"""
    def handler():
        if len(sys.argv) < 1:
            print >>sys.stderr, 'Must provide path to Python script to execute'
            sys.exit(1)
        runpy.run_path(sys.argv[0], run_name='__main__')
    master = pyseidon.Pyseidon()
    master.run(handler)

Add helper to run requested Python script

Response:
<INSERT> import pyseidon
import sys

def handle_script():
 <INSERT_END> <INSERT>   import runpy
    """
Allow the client to run an arbitrary Python script.

Here's sample usage:

```
def expensive_setup():
  ...

if __name__ == '__main__':
  expensive_setup()

  import pyseidon.handlers
  pyseidon.handlers.handle_script()
```
"""
    def handler():
        if len(sys.argv) < 1:
            print >>sys.stderr, 'Must provide path to Python script to execute'
            sys.exit(1)
        runpy.run_path(sys.argv[0], run_name='__main__')
    master = pyseidon.Pyseidon()
    master.run(handler)
 <INSERT_END> <|endoftext|> import pyseidon
import sys

def handle_script():
    import runpy
    """
Allow the client to run an arbitrary Python script.

Here's sample usage:

```
def expensive_setup():
  ...

if __name__ == '__main__':
  expensive_setup()

  import pyseidon.handlers
  pyseidon.handlers.handle_script()
```
"""
    def handler():
        if len(sys.argv) < 1:
            print >>sys.stderr, 'Must provide path to Python script to execute'
            sys.exit(1)
        runpy.run_path(sys.argv[0], run_name='__main__')
    master = pyseidon.Pyseidon()
    master.run(handler)

Prompt: Add helper to run requested Python script


from django.db import models

class Activity(models.Model):
    group = models.CharField(max_length=4)
    grouptype = models.TextField()
    groupdetail = models.TextField()
    details = models.TextField()
    disabled = models.BooleanField()
    time = models.DecimalField(decimal_places=2, max_digits=10)
    unique_together = (("group", "grouptype", "disabled", "time"),)

class ActivityEntry(models.Model):
    user = models.ManyToManyField(
        'tracker.Tbluser',
        related_name="user_foreign"
    )
    activity = models.ManyToManyField(
        Activity,
        related_name="activity_foreign"
    )
    amount = models.BigIntegerField()

    def time(self):
        return self.activity.time * self.amount

Response:
<DELETE> from timetracker.tracker.models import Tbluser
    <DELETE_END> <REPLACE_OLD> Tbluser,
 <REPLACE_NEW> 'tracker.Tbluser',
 <REPLACE_END> <|endoftext|> from django.db import models

class Activity(models.Model):
    group = models.CharField(max_length=4)
    grouptype = models.TextField()
    groupdetail = models.TextField()
    details = models.TextField()
    disabled = models.BooleanField()
    time = models.DecimalField(decimal_places=2, max_digits=10)
    unique_together = (("group", "grouptype", "disabled", "time"),)

class ActivityEntry(models.Model):
    user = models.ManyToManyField(
        'tracker.Tbluser',
        related_name="user_foreign"
    )
    activity = models.ManyToManyField(
        Activity,
        related_name="activity_foreign"
    )
    amount = models.BigIntegerField()

    def time(self):
        return self.activity.time * self.amount

Prompt:
Use the app string version of foreign keying. It prevents a circular import.

from django.db import models

class Activity(models.Model):
    group = models.CharField(max_length=4)
    grouptype = models.TextField()
    groupdetail = models.TextField()
    details = models.TextField()
    disabled = models.BooleanField()
    time = models.DecimalField(decimal_places=2, max_digits=10)
    unique_together = (("group", "grouptype", "disabled", "time"),)

class ActivityEntry(models.Model):
    from timetracker.tracker.models import Tbluser
    user = models.ManyToManyField(
        Tbluser,
        related_name="user_foreign"
    )
    activity = models.ManyToManyField(
        Activity,
        related_name="activity_foreign"
    )
    amount = models.BigIntegerField()

    def time(self):
        return self.activity.time * self.amount


from apps.decorators import on_command
from apps.slackutils import cat_token
from subprocess import check_output, CalledProcessError, STDOUT
import os
import re

@on_command(['!컴파일'])
def run(robot, channel, tokens, user, command):
    '''C, C++, Python 소스 실행시켜드림'''
    msg = ''
    if len(tokens) < 2:
        return channel, '자세한 사용방법은...'
    if tokens[0].lower() in ['c', 'c++']:
        source = cat_token(tokens, 1)
        source = re.sub('&', '&', source)
        source = re.sub('<', '<', source)
        source = re.sub('>', '>', source)
        source = re.sub(r'(#.*>)', r'\1\n', source)
        if tokens[0].lower() == 'c':
            open(user + '.c', 'w').write(source)
            msg += check_output(['gcc', user + '.c', '-o', user + '.out']).decode('utf-8')
            os.remove(user + '.c')
        else:
            open(user + '.cpp', 'w').write(source)
            try:
                msg += check_output(['g++', '-std=c++11' ,user + '.cpp', '-o', user + '.out'], stderr=STDOUT).decode('utf-8')
            except CalledProcessError as e:
                msg += e.output.decode('utf-8')
                return channel, msg
            os.remove(user + '.cpp')
        try:
            msg += check_output(['./' + user + '.out']).decode('utf-8')
        except CalledProcessError as e:
            msg += '> :warning: WARNING : Your program returned exit status `' + str(e.args[0]) +'`\n'
            msg += e.output.decode('utf-8')
        os.remove(user + '.out')
    return channel, msg

ADD FEATURE : simple C/C++ compiler

ADD FEATURE : simple C/C++ compiler

Response:
<REPLACE_OLD>  <REPLACE_NEW> from apps.decorators import on_command
from apps.slackutils import cat_token
from subprocess import check_output, CalledProcessError, STDOUT
import os
import re

@on_command(['!컴파일'])
def run(robot, channel, tokens, user, command):
    '''C, C++, Python 소스 실행시켜드림'''
    msg = ''
    if len(tokens) < 2:
        return channel, '자세한 사용방법은...'
    if tokens[0].lower() in ['c', 'c++']:
        source = cat_token(tokens, 1)
        source = re.sub('&', '&', source)
        source = re.sub('<', '<', source)
        source = re.sub('>', '>', source)
        source = re.sub(r'(#.*>)', r'\1\n', source)
        if tokens[0].lower() == 'c':
            open(user + '.c', 'w').write(source)
            msg += check_output(['gcc', user + '.c', '-o', user + '.out']).decode('utf-8')
            os.remove(user + '.c')
        else:
            open(user + '.cpp', 'w').write(source)
            try:
                msg += check_output(['g++', '-std=c++11' ,user + '.cpp', '-o', user + '.out'], stderr=STDOUT).decode('utf-8')
            except CalledProcessError as e:
                msg += e.output.decode('utf-8')
                return channel, msg
            os.remove(user + '.cpp')
        try:
            msg += check_output(['./' + user + '.out']).decode('utf-8')
        except CalledProcessError as e:
            msg += '> :warning: WARNING : Your program returned exit status `' + str(e.args[0]) +'`\n'
            msg += e.output.decode('utf-8')
        os.remove(user + '.out')
    return channel, msg

 <REPLACE_END> <|endoftext|> from apps.decorators import on_command
from apps.slackutils import cat_token
from subprocess import check_output, CalledProcessError, STDOUT
import os
import re

@on_command(['!컴파일'])
def run(robot, channel, tokens, user, command):
    '''C, C++, Python 소스 실행시켜드림'''
    msg = ''
    if len(tokens) < 2:
        return channel, '자세한 사용방법은...'
    if tokens[0].lower() in ['c', 'c++']:
        source = cat_token(tokens, 1)
        source = re.sub('&', '&', source)
        source = re.sub('<', '<', source)
        source = re.sub('>', '>', source)
        source = re.sub(r'(#.*>)', r'\1\n', source)
        if tokens[0].lower() == 'c':
            open(user + '.c', 'w').write(source)
            msg += check_output(['gcc', user + '.c', '-o', user + '.out']).decode('utf-8')
            os.remove(user + '.c')
        else:
            open(user + '.cpp', 'w').write(source)
            try:
                msg += check_output(['g++', '-std=c++11' ,user + '.cpp', '-o', user + '.out'], stderr=STDOUT).decode('utf-8')
            except CalledProcessError as e:
                msg += e.output.decode('utf-8')
                return channel, msg
            os.remove(user + '.cpp')
        try:
            msg += check_output(['./' + user + '.out']).decode('utf-8')
        except CalledProcessError as e:
            msg += '> :warning: WARNING : Your program returned exit status `' + str(e.args[0]) +'`\n'
            msg += e.output.decode('utf-8')
        os.remove(user + '.out')
    return channel, msg

Prompt: ADD FEATURE : simple C/C++ compiler


import sys
import logging

from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver as get_libcloud_driver

from pod_manager.settings import LOG_LEVEL, LOG_FORMAT
from pod_manager.settings import PROVIDER, PROVIDER_CREDENTIALS, PROVIDER_KWARGS

__all__ = [
    'get_logger',
    'get_driver'
]

def get_logger(name):
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    handler = logging.StreamHandler(sys.__stdout__)
    formatter = logging.Formatter(LOG_FORMAT)
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    return logger

def get_driver():
    cls = get_libcloud_driver(PROVIDER)
    driver = cls(*PROVIDER_CREDENTIALS, **PROVIDER_KWARGS)
    return driver

Response:
<REPLACE_OLD> logging

__all__ <REPLACE_NEW> sys
import logging

from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver as get_libcloud_driver

from pod_manager.settings import LOG_LEVEL, LOG_FORMAT
from pod_manager.settings import PROVIDER, PROVIDER_CREDENTIALS, PROVIDER_KWARGS

__all__ <REPLACE_END> <REPLACE_OLD> 'get_logger'
]

def <REPLACE_NEW> 'get_logger',
    'get_driver'
]

def <REPLACE_END> <REPLACE_OLD> # TODO: set level, add handler
 <REPLACE_NEW> logger.setLevel(logging.DEBUG)
    handler = logging.StreamHandler(sys.__stdout__)
    formatter = logging.Formatter(LOG_FORMAT)
    handler.setFormatter(formatter)
    logger.addHandler(handler)
 <REPLACE_END> <REPLACE_OLD> logger
 <REPLACE_NEW> logger

def get_driver():
    cls = get_libcloud_driver(PROVIDER)
    driver = cls(*PROVIDER_CREDENTIALS, **PROVIDER_KWARGS)
    return driver
 <REPLACE_END> <|endoftext|> import sys
import logging

from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver as get_libcloud_driver

from pod_manager.settings import LOG_LEVEL, LOG_FORMAT
from pod_manager.settings import PROVIDER, PROVIDER_CREDENTIALS, PROVIDER_KWARGS

__all__ = [
    'get_logger',
    'get_driver'
]

def get_logger(name):
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    handler = logging.StreamHandler(sys.__stdout__)
    formatter = logging.Formatter(LOG_FORMAT)
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    return logger

def get_driver():
    cls = get_libcloud_driver(PROVIDER)
    driver = cls(*PROVIDER_CREDENTIALS, **PROVIDER_KWARGS)
    return driver

Prompt:
Modify get_logger to set level and formatter, add get_driver method.

import logging

__all__ = [
    'get_logger'
]

def get_logger(name):
    logger = logging.getLogger(name)
    # TODO: set level, add handler
    return logger


#!/usr/bin/python

import yaml
import os.path

_config_file_base_name = 'mediawords.yml'
_config_file_name = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'mediawords.yml'))

_defaults_config_file_base_name = 'defaults.yml'
_defaults_config_file_name = os.path.abspath(os.path.join(os.path.dirname(__file__), '../config', _defaults_config_file_base_name))

def _load_yml( file_path ):
    yml_file = open(file_path, 'rb')
    config_file = yaml.load( yml_file )

    return config_file

def deep_merge( original, update ):
    for key, value in update.iteritems():
        if not key in original:
            original[ key ] = value
        elif isinstance( value, dict) and isinstance( original[key], dict):
            deep_merge( original[ key ], value )

    return original

def read_config():

    config_file   = _load_yml( _config_file_name )
    defaults_file = _load_yml( _defaults_config_file_name )

    # print "config_file"
    # print config_file
    # print "defaults_file"
    # print defaults_file

    config_file = deep_merge( config_file, defaults_file )

    # print "Merged"
    # print config_file

    return config_file

Response:
<REPLACE_OLD> 'mediawords.yml'))

def read_config():
 <REPLACE_NEW> 'mediawords.yml'))

_defaults_config_file_base_name = 'defaults.yml'
_defaults_config_file_name = os.path.abspath(os.path.join(os.path.dirname(__file__), '../config', _defaults_config_file_base_name))

def _load_yml( file_path ):
 <REPLACE_END> <REPLACE_OLD> open(_config_file_name, <REPLACE_NEW> open(file_path, <REPLACE_END> <INSERT>
    return config_file

def deep_merge( original, update ):
    for key, value in update.iteritems():
        if not key in original:
            original[ key ] = value
        elif isinstance( value, dict) and isinstance( original[key], dict):
            deep_merge( original[ key ], value )

    return original

def read_config():

    config_file   = _load_yml( _config_file_name )
    defaults_file = _load_yml( _defaults_config_file_name )

    # print "config_file"
    # print config_file
    # print "defaults_file"
    # print defaults_file

    config_file = deep_merge( config_file, defaults_file )

    # print "Merged"
    # print config_file

    <INSERT_END> <|endoftext|> #!/usr/bin/python

import yaml
import os.path

_config_file_base_name = 'mediawords.yml'
_config_file_name = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'mediawords.yml'))

_defaults_config_file_base_name = 'defaults.yml'
_defaults_config_file_name = os.path.abspath(os.path.join(os.path.dirname(__file__), '../config', _defaults_config_file_base_name))

def _load_yml( file_path ):
    yml_file = open(file_path, 'rb')
    config_file = yaml.load( yml_file )

    return config_file

def deep_merge( original, update ):
    for key, value in update.iteritems():
        if not key in original:
            original[ key ] = value
        elif isinstance( value, dict) and isinstance( original[key], dict):
            deep_merge( original[ key ], value )

    return original

def read_config():

    config_file   = _load_yml( _config_file_name )
    defaults_file = _load_yml( _defaults_config_file_name )

    # print "config_file"
    # print config_file
    # print "defaults_file"
    # print defaults_file

    config_file = deep_merge( config_file, defaults_file )

    # print "Merged"
    # print config_file

    return config_file

Prompt:
Read the defaults config file and merge it with mediawords.yml

#!/usr/bin/python

import yaml
import os.path

_config_file_base_name = 'mediawords.yml'
_config_file_name = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'mediawords.yml'))

def read_config():
    yml_file = open(_config_file_name, 'rb')
    config_file = yaml.load( yml_file )
    return config_file


#!/usr/bin/env python

from __future__ import division

import sys
import timeit

import numpy

from rank_filter import lineRankOrderFilter

def benchmark():
    input_array = numpy.random.normal(size=(100, 101, 102))
    output_array = numpy.empty_like(input_array)

    lineRankOrderFilter(input_array, 25, 0.5, 0, output_array)

def main(*argv):
    times = 10

    avg_time = timeit.timeit(
        "benchmark()",
        setup="from __main__ import benchmark",
        number=times
    ) / times

    print(
        "Of " + repr(times) + " trials," +
        " the average runtime = " + repr(avg_time) + "s."
    )

    return(0)

if __name__ == '__main__':
    sys.exit(main(*sys.argv))

Use Python 3 division on Python 2

Response:
<REPLACE_OLD> python

import <REPLACE_NEW> python

from __future__ import division

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

from __future__ import division

import sys
import timeit

import numpy

from rank_filter import lineRankOrderFilter

def benchmark():
    input_array = numpy.random.normal(size=(100, 101, 102))
    output_array = numpy.empty_like(input_array)

    lineRankOrderFilter(input_array, 25, 0.5, 0, output_array)

def main(*argv):
    times = 10

    avg_time = timeit.timeit(
        "benchmark()",
        setup="from __main__ import benchmark",
        number=times
    ) / times

    print(
        "Of " + repr(times) + " trials," +
        " the average runtime = " + repr(avg_time) + "s."
    )

    return(0)

if __name__ == '__main__':
    sys.exit(main(*sys.argv))

Prompt:
Use Python 3 division on Python 2

Make sure that floating point division is used on Python 2. This
basically happens anyways as we have a floating point value divided by
an integral value. Still it is good to ensure that our average doesn't
get truncated by accident.

#!/usr/bin/env python

import sys
import timeit

import numpy

from rank_filter import lineRankOrderFilter

def benchmark():
    input_array = numpy.random.normal(size=(100, 101, 102))
    output_array = numpy.empty_like(input_array)

    lineRankOrderFilter(input_array, 25, 0.5, 0, output_array)

def main(*argv):
    times = 10

    avg_time = timeit.timeit(
        "benchmark()",
        setup="from __main__ import benchmark",
        number=times
    ) / times

    print(
        "Of " + repr(times) + " trials," +
        " the average runtime = " + repr(avg_time) + "s."
    )

    return(0)

if __name__ == '__main__':
    sys.exit(main(*sys.argv))


import os

BASE_PATH = os.path.abspath(os.path.dirname(__file__))
MEDIA_ROOT = os.path.normpath(os.path.join(BASE_PATH, 'media'))

SECRET_KEY = 'not secret'
INSTALLED_APPS = ('simpleimages', 'tests')
TEMPLATE_DEBUG = DEBUG = True
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
    },
}

Use in memory database for tests

Use in memory database for tests

Response:
<DELETE>     'NAME': 'imagekit.db',
    <DELETE_END> <|endoftext|> import os

BASE_PATH = os.path.abspath(os.path.dirname(__file__))
MEDIA_ROOT = os.path.normpath(os.path.join(BASE_PATH, 'media'))

SECRET_KEY = 'not secret'
INSTALLED_APPS = ('simpleimages', 'tests')
TEMPLATE_DEBUG = DEBUG = True
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
    },
}

Prompt:
Use in memory database for tests

import os

BASE_PATH = os.path.abspath(os.path.dirname(__file__))
MEDIA_ROOT = os.path.normpath(os.path.join(BASE_PATH, 'media'))

SECRET_KEY = 'not secret'
INSTALLED_APPS = ('simpleimages', 'tests')
TEMPLATE_DEBUG = DEBUG = True
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'imagekit.db',
    },
}