import json

from changes.api.serializer import Serializer, register
from changes.models import Plan, Step

@register(Plan)
class PlanSerializer(Serializer):
    def serialize(self, instance, attrs):
        return {
            'id': instance.id.hex,
            'name': instance.label,
            'steps': list(instance.steps),
            'dateCreated': instance.date_created,
            'dateModified': instance.date_modified,
        }

@register(Step)
class StepSerializer(Serializer):
    def serialize(self, instance, attrs):
        implementation = instance.get_implementation()

        return {
            'id': instance.id.hex,
            'implementation': instance.implementation,
            'order': instance.order,
            'name': implementation.get_label() if implementation else '',
            'data': json.dumps(dict(instance.data or {})),
            'dateCreated': instance.date_created,
        }

Handle optional value in step.data

Handle optional value in step.data

Response:
<REPLACE_OLD> json.dumps(dict(instance.data)),
 <REPLACE_NEW> json.dumps(dict(instance.data or {})),
 <REPLACE_END> <|endoftext|> import json

from changes.api.serializer import Serializer, register
from changes.models import Plan, Step

@register(Plan)
class PlanSerializer(Serializer):
    def serialize(self, instance, attrs):
        return {
            'id': instance.id.hex,
            'name': instance.label,
            'steps': list(instance.steps),
            'dateCreated': instance.date_created,
            'dateModified': instance.date_modified,
        }

@register(Step)
class StepSerializer(Serializer):
    def serialize(self, instance, attrs):
        implementation = instance.get_implementation()

        return {
            'id': instance.id.hex,
            'implementation': instance.implementation,
            'order': instance.order,
            'name': implementation.get_label() if implementation else '',
            'data': json.dumps(dict(instance.data or {})),
            'dateCreated': instance.date_created,
        }

Prompt:
Handle optional value in step.data

import json

from changes.api.serializer import Serializer, register
from changes.models import Plan, Step

@register(Plan)
class PlanSerializer(Serializer):
    def serialize(self, instance, attrs):
        return {
            'id': instance.id.hex,
            'name': instance.label,
            'steps': list(instance.steps),
            'dateCreated': instance.date_created,
            'dateModified': instance.date_modified,
        }

@register(Step)
class StepSerializer(Serializer):
    def serialize(self, instance, attrs):
        implementation = instance.get_implementation()

        return {
            'id': instance.id.hex,
            'implementation': instance.implementation,
            'order': instance.order,
            'name': implementation.get_label() if implementation else '',
            'data': json.dumps(dict(instance.data)),
            'dateCreated': instance.date_created,
        }


import atexit
import os
import tempfile

tmpdir = tempfile.TemporaryDirectory()
os.environ.setdefault('DATA_DIR', tmpdir.name)

from pretix.settings import *  # NOQA

DATA_DIR = tmpdir.name
LOG_DIR = os.path.join(DATA_DIR, 'logs')
MEDIA_ROOT = os.path.join(DATA_DIR, 'media')

atexit.register(tmpdir.cleanup)

EMAIL_BACKEND = 'django.core.mail.outbox'

COMPRESS_ENABLED = COMPRESS_OFFLINE = False

DEBUG = True

PASSWORD_HASHERS = ['django.contrib.auth.hashers.MD5PasswordHasher']

# Disable celery
CELERY_ALWAYS_EAGER = True
HAS_CELERY = False

# Don't use redis
SESSION_ENGINE = "django.contrib.sessions.backends.db"
HAS_REDIS = False
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
    }
}

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': ':memory:'
    }
}

Response:
<INSERT> }
}

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': ':memory:'
    <INSERT_END> <|endoftext|> import atexit
import os
import tempfile

tmpdir = tempfile.TemporaryDirectory()
os.environ.setdefault('DATA_DIR', tmpdir.name)

from pretix.settings import *  # NOQA

DATA_DIR = tmpdir.name
LOG_DIR = os.path.join(DATA_DIR, 'logs')
MEDIA_ROOT = os.path.join(DATA_DIR, 'media')

atexit.register(tmpdir.cleanup)

EMAIL_BACKEND = 'django.core.mail.outbox'

COMPRESS_ENABLED = COMPRESS_OFFLINE = False

DEBUG = True

PASSWORD_HASHERS = ['django.contrib.auth.hashers.MD5PasswordHasher']

# Disable celery
CELERY_ALWAYS_EAGER = True
HAS_CELERY = False

# Don't use redis
SESSION_ENGINE = "django.contrib.sessions.backends.db"
HAS_REDIS = False
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
    }
}

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': ':memory:'
    }
}

Prompt:
Test on SQLite if not configured otherwise

import atexit
import os
import tempfile

tmpdir = tempfile.TemporaryDirectory()
os.environ.setdefault('DATA_DIR', tmpdir.name)

from pretix.settings import *  # NOQA

DATA_DIR = tmpdir.name
LOG_DIR = os.path.join(DATA_DIR, 'logs')
MEDIA_ROOT = os.path.join(DATA_DIR, 'media')

atexit.register(tmpdir.cleanup)

EMAIL_BACKEND = 'django.core.mail.outbox'

COMPRESS_ENABLED = COMPRESS_OFFLINE = False

DEBUG = True

PASSWORD_HASHERS = ['django.contrib.auth.hashers.MD5PasswordHasher']

# Disable celery
CELERY_ALWAYS_EAGER = True
HAS_CELERY = False

# Don't use redis
SESSION_ENGINE = "django.contrib.sessions.backends.db"
HAS_REDIS = False
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
    }
}


from tmlib.workflow.args import BatchArguments
from tmlib.workflow.args import SubmissionArguments
from tmlib.workflow.args import Argument
from tmlib.workflow import register_batch_args
from tmlib.workflow import register_submission_args

@register_batch_args('align')
class AlignBatchArguments(BatchArguments):

    ref_cycle = Argument(
        type=int, required=True, flag='c',
        help='''zero-based index of the cycle whose sites should be used
            as reference
        '''
    )

    ref_wavelength = Argument(
        type=str, required=True, flag='w',
        help='name of the wavelength whose images should be used as reference'
    )

    batch_size = Argument(
        type=int, default=100, flag='b',
        help='number of image files that should be processed per job'
    )

@register_submission_args('align')
class AlignSubmissionArguments(SubmissionArguments):

    pass

Response:
<REPLACE_OLD> default=10, <REPLACE_NEW> default=100, <REPLACE_END> <|endoftext|> from tmlib.workflow.args import BatchArguments
from tmlib.workflow.args import SubmissionArguments
from tmlib.workflow.args import Argument
from tmlib.workflow import register_batch_args
from tmlib.workflow import register_submission_args

@register_batch_args('align')
class AlignBatchArguments(BatchArguments):

    ref_cycle = Argument(
        type=int, required=True, flag='c',
        help='''zero-based index of the cycle whose sites should be used
            as reference
        '''
    )

    ref_wavelength = Argument(
        type=str, required=True, flag='w',
        help='name of the wavelength whose images should be used as reference'
    )

    batch_size = Argument(
        type=int, default=100, flag='b',
        help='number of image files that should be processed per job'
    )

@register_submission_args('align')
class AlignSubmissionArguments(SubmissionArguments):

    pass

Prompt:
Increase default batch size for align step

from tmlib.workflow.args import BatchArguments
from tmlib.workflow.args import SubmissionArguments
from tmlib.workflow.args import Argument
from tmlib.workflow import register_batch_args
from tmlib.workflow import register_submission_args

@register_batch_args('align')
class AlignBatchArguments(BatchArguments):

    ref_cycle = Argument(
        type=int, required=True, flag='c',
        help='''zero-based index of the cycle whose sites should be used
            as reference
        '''
    )

    ref_wavelength = Argument(
        type=str, required=True, flag='w',
        help='name of the wavelength whose images should be used as reference'
    )

    batch_size = Argument(
        type=int, default=10, flag='b',
        help='number of image files that should be processed per job'
    )

@register_submission_args('align')
class AlignSubmissionArguments(SubmissionArguments):

    pass


import tornado.ioloop
import tornado.web
import logging
import motor
from settings import routing
from tornado.options import options
import os

if not os.path.exists(options.log_dir):
    os.makedirs(options.log_dir)

logging.basicConfig(
    format='%(asctime)s [%(name)s] %(levelname)s: %(message)s',
    filename='%s/%s' % (options.log_dir, options.log_file),
    level=logging.DEBUG
)

logging.getLogger('INIT').info('Connecting to mongodb at: %s' % options.db_address)
ioLoop = tornado.ioloop.IOLoop.current()
mongodb = ioLoop.run_sync(motor.MotorClient(options.db_address).open)
app = tornado.web.Application(routing, db=mongodb, autoreload=options.autoreload)

app.listen(options.port)

if __name__ == "__main__":
    try:
        logging.info("Starting HTTP server on port %d" % options.port)
        ioLoop.start()
    except KeyboardInterrupt:
        logging.info("Shutting down server HTTP proxy on port %d" % options.port)
        ioLoop.stop()

Add to log db connection url

Add to log db connection url

Response:
<REPLACE_OLD> level=logging.DEBUG
)

ioLoop <REPLACE_NEW> level=logging.DEBUG
)

logging.getLogger('INIT').info('Connecting to mongodb at: %s' % options.db_address)
ioLoop <REPLACE_END> <|endoftext|> import tornado.ioloop
import tornado.web
import logging
import motor
from settings import routing
from tornado.options import options
import os

if not os.path.exists(options.log_dir):
    os.makedirs(options.log_dir)

logging.basicConfig(
    format='%(asctime)s [%(name)s] %(levelname)s: %(message)s',
    filename='%s/%s' % (options.log_dir, options.log_file),
    level=logging.DEBUG
)

logging.getLogger('INIT').info('Connecting to mongodb at: %s' % options.db_address)
ioLoop = tornado.ioloop.IOLoop.current()
mongodb = ioLoop.run_sync(motor.MotorClient(options.db_address).open)
app = tornado.web.Application(routing, db=mongodb, autoreload=options.autoreload)

app.listen(options.port)

if __name__ == "__main__":
    try:
        logging.info("Starting HTTP server on port %d" % options.port)
        ioLoop.start()
    except KeyboardInterrupt:
        logging.info("Shutting down server HTTP proxy on port %d" % options.port)
        ioLoop.stop()

Prompt:
Add to log db connection url

import tornado.ioloop
import tornado.web
import logging
import motor
from settings import routing
from tornado.options import options
import os

if not os.path.exists(options.log_dir):
    os.makedirs(options.log_dir)

logging.basicConfig(
    format='%(asctime)s [%(name)s] %(levelname)s: %(message)s',
    filename='%s/%s' % (options.log_dir, options.log_file),
    level=logging.DEBUG
)

ioLoop = tornado.ioloop.IOLoop.current()
mongodb = ioLoop.run_sync(motor.MotorClient(options.db_address).open)
app = tornado.web.Application(routing, db=mongodb, autoreload=options.autoreload)

app.listen(options.port)

if __name__ == "__main__":
    try:
        logging.info("Starting HTTP server on port %d" % options.port)
        ioLoop.start()
    except KeyboardInterrupt:
        logging.info("Shutting down server HTTP proxy on port %d" % options.port)
        ioLoop.stop()


import hashlib
from django import template

register = template.Library()

@register.filter
def to_gravatar_url(email):
    return ('https://gravatar.com/avatar/%s?d=retro' %
            hashlib.md5((email or '').strip().lower().encode('utf-8')).hexdigest())

Fix gravatar hashing error on py3

Fix gravatar hashing error on py3

Response:
<REPLACE_OLD> '').strip().lower()).hexdigest())
 <REPLACE_NEW> '').strip().lower().encode('utf-8')).hexdigest())
 <REPLACE_END> <|endoftext|> import hashlib
from django import template

register = template.Library()

@register.filter
def to_gravatar_url(email):
    return ('https://gravatar.com/avatar/%s?d=retro' %
            hashlib.md5((email or '').strip().lower().encode('utf-8')).hexdigest())

Prompt:
Fix gravatar hashing error on py3

import hashlib
from django import template

register = template.Library()

@register.filter
def to_gravatar_url(email):
    return ('https://gravatar.com/avatar/%s?d=retro' %
            hashlib.md5((email or '').strip().lower()).hexdigest())


#   Foremast - Pipeline Tooling
#
#   Copyright 2016 Gogo, LLC
#
#   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.
"""Create manual Pipeline for Spinnaker."""
from ..utils.lookups import FileLookup
from .clean_pipelines import delete_pipeline
from .create_pipeline import SpinnakerPipeline

class SpinnakerPipelineManual(SpinnakerPipeline):
    """Manual JSON configured Spinnaker Pipelines."""

    def create_pipeline(self):
        """Use JSON files to create Pipelines."""
        self.log.info('Uploading manual Pipelines: %s')
        lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir)

        for json_file in self.settings['pipeline']['pipeline_files']:
            delete_pipeline(app=self.app_name, pipeline_name=json_file)

            json_dict = lookup.json(filename=json_file)
            json_dict['name'] = json_file
            self.post_pipeline(json_dict)

        return True

Delete manual Pipeline before creating

Response:
<INSERT> .clean_pipelines import delete_pipeline
from <INSERT_END> <INSERT> delete_pipeline(app=self.app_name, pipeline_name=json_file)

            <INSERT_END> <|endoftext|> #   Foremast - Pipeline Tooling
#
#   Copyright 2016 Gogo, LLC
#
#   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.
"""Create manual Pipeline for Spinnaker."""
from ..utils.lookups import FileLookup
from .clean_pipelines import delete_pipeline
from .create_pipeline import SpinnakerPipeline

class SpinnakerPipelineManual(SpinnakerPipeline):
    """Manual JSON configured Spinnaker Pipelines."""

    def create_pipeline(self):
        """Use JSON files to create Pipelines."""
        self.log.info('Uploading manual Pipelines: %s')
        lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir)

        for json_file in self.settings['pipeline']['pipeline_files']:
            delete_pipeline(app=self.app_name, pipeline_name=json_file)

            json_dict = lookup.json(filename=json_file)
            json_dict['name'] = json_file
            self.post_pipeline(json_dict)

        return True

Prompt:
fix: Delete manual Pipeline before creating

See also: #72

#   Foremast - Pipeline Tooling
#
#   Copyright 2016 Gogo, LLC
#
#   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.
"""Create manual Pipeline for Spinnaker."""
from ..utils.lookups import FileLookup
from .create_pipeline import SpinnakerPipeline

class SpinnakerPipelineManual(SpinnakerPipeline):
    """Manual JSON configured Spinnaker Pipelines."""

    def create_pipeline(self):
        """Use JSON files to create Pipelines."""
        self.log.info('Uploading manual Pipelines: %s')
        lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir)

        for json_file in self.settings['pipeline']['pipeline_files']:
            json_dict = lookup.json(filename=json_file)
            json_dict['name'] = json_file
            self.post_pipeline(json_dict)

        return True


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

import hashlib

from django.utils.http import urlencode, urlquote
from django.utils.encoding import force_bytes

from .. import register

@register.simple_tag()
def get_gravatar_url(user, size, rating='g', default='identicon'):
    url = "http://www.gravatar.com/avatar/"
    hash = hashlib.md5(force_bytes(user.email.strip().lower().encode('utf_8'))).hexdigest()
    data = urlencode({'d': urlquote(default), 's': str(size), 'r': rating})
    return "".join((url, hash, '?', data))

Response:
<REPLACE_OLD> urlquote

from <REPLACE_NEW> urlquote
from django.utils.encoding import force_bytes

from <REPLACE_END> <REPLACE_OLD> hashlib.md5(user.email.strip().lower()).hexdigest()
 <REPLACE_NEW> hashlib.md5(force_bytes(user.email.strip().lower().encode('utf_8'))).hexdigest()
 <REPLACE_END> <|endoftext|> #-*- coding: utf-8 -*-

import hashlib

from django.utils.http import urlencode, urlquote
from django.utils.encoding import force_bytes

from .. import register

@register.simple_tag()
def get_gravatar_url(user, size, rating='g', default='identicon'):
    url = "http://www.gravatar.com/avatar/"
    hash = hashlib.md5(force_bytes(user.email.strip().lower().encode('utf_8'))).hexdigest()
    data = urlencode({'d': urlquote(default), 's': str(size), 'r': rating})
    return "".join((url, hash, '?', data))

Prompt:
Use django utils force_bytes to arguments of hashlib

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

import hashlib

from django.utils.http import urlencode, urlquote

from .. import register

@register.simple_tag()
def get_gravatar_url(user, size, rating='g', default='identicon'):
    url = "http://www.gravatar.com/avatar/"
    hash = hashlib.md5(user.email.strip().lower()).hexdigest()
    data = urlencode({'d': urlquote(default), 's': str(size), 'r': rating})
    return "".join((url, hash, '?', data))


import unittest
import librepo
from librepo import LibrepoException

class TestCaseResult(unittest.TestCase):

    def test_result_getinfo(self):
        r = librepo.Result()
        self.assertTrue(r)

        self.assertRaises(ValueError, r.getinfo, 99999999)
        self.assertFalse(r.getinfo(librepo.LRR_YUM_REPO))
        self.assertFalse(r.getinfo(librepo.LRR_YUM_REPOMD))
        self.assertRaises(LibrepoException, r.getinfo, librepo.LRR_YUM_TIMESTAMP)

    def test_result_attrs(self):
        r = librepo.Result()
        self.assertTrue(r)

        self.assertRaises(AttributeError, getattr, r, 'foobar_attr')

        # Attrs should not be filled (that's why None or
        # LibrepoException is expected), but they definitelly
        # should exists (not AttributeError should be raised)
        self.assertFalse(r.yum_repo)
        self.assertFalse(r.yum_repomd)
        self.assertRaises(LibrepoException, getattr, r, 'yum_timestamp')

Add tests for Result object

Tests: Add tests for Result object

Response:
<INSERT> import unittest
import librepo
from librepo import LibrepoException

class TestCaseResult(unittest.TestCase):

 <INSERT_END> <INSERT>   def test_result_getinfo(self):
        r = librepo.Result()
        self.assertTrue(r)

        self.assertRaises(ValueError, r.getinfo, 99999999)
        self.assertFalse(r.getinfo(librepo.LRR_YUM_REPO))
        self.assertFalse(r.getinfo(librepo.LRR_YUM_REPOMD))
        self.assertRaises(LibrepoException, r.getinfo, librepo.LRR_YUM_TIMESTAMP)

    def test_result_attrs(self):
        r = librepo.Result()
        self.assertTrue(r)

        self.assertRaises(AttributeError, getattr, r, 'foobar_attr')

        # Attrs should not be filled (that's why None or
        # LibrepoException is expected), but they definitelly
        # should exists (not AttributeError should be raised)
        self.assertFalse(r.yum_repo)
        self.assertFalse(r.yum_repomd)
        self.assertRaises(LibrepoException, getattr, r, 'yum_timestamp')
 <INSERT_END> <|endoftext|> import unittest
import librepo
from librepo import LibrepoException

class TestCaseResult(unittest.TestCase):

    def test_result_getinfo(self):
        r = librepo.Result()
        self.assertTrue(r)

        self.assertRaises(ValueError, r.getinfo, 99999999)
        self.assertFalse(r.getinfo(librepo.LRR_YUM_REPO))
        self.assertFalse(r.getinfo(librepo.LRR_YUM_REPOMD))
        self.assertRaises(LibrepoException, r.getinfo, librepo.LRR_YUM_TIMESTAMP)

    def test_result_attrs(self):
        r = librepo.Result()
        self.assertTrue(r)

        self.assertRaises(AttributeError, getattr, r, 'foobar_attr')

        # Attrs should not be filled (that's why None or
        # LibrepoException is expected), but they definitelly
        # should exists (not AttributeError should be raised)
        self.assertFalse(r.yum_repo)
        self.assertFalse(r.yum_repomd)
        self.assertRaises(LibrepoException, getattr, r, 'yum_timestamp')

Prompt: Tests: Add tests for Result object


#!/usr/bin/env python
#
# Tests for dakota.dakota_base module.
#
# Call with:
#   $ nosetests -sv
#
# Mark Piper (mark.piper@colorado.edu)

from nose.tools import *
from dakota.dakota_base import DakotaBase

# Helpers --------------------------------------------------------------

class Concrete(DakotaBase):
    """A subclass of DakotaBase used for testing."""
    def __init__(self):
        DakotaBase.__init__(self)

# Fixtures -------------------------------------------------------------

def setup_module():
    """Called before any tests are performed."""
    print('\n*** DakotaBase tests')
    global c
    c = Concrete()

def teardown_module():
    """Called after all tests have completed."""
    pass

# Tests ----------------------------------------------------------------

@raises(TypeError)
def test_instantiate():
    """Test whether DakotaBase fails to instantiate."""
    d = DakotaBase()

def test_environment_block():
    """Test type of environment_block method results."""
    s = c.environment_block()
    assert_true(type(s) is str)

def test_method_block():
    """Test type of method_block method results."""
    s = c.method_block()
    assert_true(type(s) is str)

def test_variables_block():
    """Test type of variables_block method results."""
    s = c.variables_block()
    assert_true(type(s) is str)

def test_interface_block():
    """Test type of interface_block method results."""
    s = c.interface_block()
    assert_true(type(s) is str)

def test_responses_block():
    """Test type of responses_block method results."""
    s = c.responses_block()
    assert_true(type(s) is str)

def test_autogenerate_descriptors():
    """Test autogenerate_descriptors method."""
    c.n_variables, c.n_responses = 1, 1
    c.autogenerate_descriptors()
    assert_true(len(c.variable_descriptors) == 1)
    assert_true(len(c.response_descriptors) == 1)

Add tests for dakota.dakota_base module

Response:
<REPLACE_OLD> (mark.piper@colorado.edu)

import os
import filecmp
from <REPLACE_NEW> (mark.piper@colorado.edu)

from <REPLACE_END> <REPLACE_OLD> DakotaBase

# <REPLACE_NEW> DakotaBase

# Helpers --------------------------------------------------------------

class Concrete(DakotaBase):
    """A subclass of DakotaBase used for testing."""
    def __init__(self):
        DakotaBase.__init__(self)

# <REPLACE_END> <REPLACE_OLD> tests')

def <REPLACE_NEW> tests')
    global c
    c = Concrete()

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

def test_environment_block():
    """Test type of environment_block method results."""
    s = c.environment_block()
    assert_true(type(s) is str)

def test_method_block():
    """Test type of method_block method results."""
    s = c.method_block()
    assert_true(type(s) is str)

def test_variables_block():
    """Test type of variables_block method results."""
    s = c.variables_block()
    assert_true(type(s) is str)

def test_interface_block():
    """Test type of interface_block method results."""
    s = c.interface_block()
    assert_true(type(s) is str)

def test_responses_block():
    """Test type of responses_block method results."""
    s = c.responses_block()
    assert_true(type(s) is str)

def test_autogenerate_descriptors():
    """Test autogenerate_descriptors method."""
    c.n_variables, c.n_responses = 1, 1
    c.autogenerate_descriptors()
    assert_true(len(c.variable_descriptors) == 1)
    assert_true(len(c.response_descriptors) == 1)
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
#
# Tests for dakota.dakota_base module.
#
# Call with:
#   $ nosetests -sv
#
# Mark Piper (mark.piper@colorado.edu)

from nose.tools import *
from dakota.dakota_base import DakotaBase

# Helpers --------------------------------------------------------------

class Concrete(DakotaBase):
    """A subclass of DakotaBase used for testing."""
    def __init__(self):
        DakotaBase.__init__(self)

# Fixtures -------------------------------------------------------------

def setup_module():
    """Called before any tests are performed."""
    print('\n*** DakotaBase tests')
    global c
    c = Concrete()

def teardown_module():
    """Called after all tests have completed."""
    pass

# Tests ----------------------------------------------------------------

@raises(TypeError)
def test_instantiate():
    """Test whether DakotaBase fails to instantiate."""
    d = DakotaBase()

def test_environment_block():
    """Test type of environment_block method results."""
    s = c.environment_block()
    assert_true(type(s) is str)

def test_method_block():
    """Test type of method_block method results."""
    s = c.method_block()
    assert_true(type(s) is str)

def test_variables_block():
    """Test type of variables_block method results."""
    s = c.variables_block()
    assert_true(type(s) is str)

def test_interface_block():
    """Test type of interface_block method results."""
    s = c.interface_block()
    assert_true(type(s) is str)

def test_responses_block():
    """Test type of responses_block method results."""
    s = c.responses_block()
    assert_true(type(s) is str)

def test_autogenerate_descriptors():
    """Test autogenerate_descriptors method."""
    c.n_variables, c.n_responses = 1, 1
    c.autogenerate_descriptors()
    assert_true(len(c.variable_descriptors) == 1)
    assert_true(len(c.response_descriptors) == 1)

Prompt:
Add tests for dakota.dakota_base module

Make a subclass of DakotaBase to use for testing. Add tests for the
"block" sections used to define an input file.

#!/usr/bin/env python
#
# Tests for dakota.dakota_base module.
#
# Call with:
#   $ nosetests -sv
#
# Mark Piper (mark.piper@colorado.edu)

import os
import filecmp
from nose.tools import *
from dakota.dakota_base import DakotaBase

# Fixtures -------------------------------------------------------------

def setup_module():
    """Called before any tests are performed."""
    print('\n*** DakotaBase tests')

def teardown_module():
    """Called after all tests have completed."""
    pass

# Tests ----------------------------------------------------------------

@raises(TypeError)
def test_instantiate():
    """Test whether DakotaBase fails to instantiate."""
    d = DakotaBase()


#!/usr/bin/env python

import setuptools

import samsungctl

setuptools.setup(
    name=samsungctl.__title__,
    version=samsungctl.__version__,
    description=samsungctl.__doc__,
    url=samsungctl.__url__,
    author=samsungctl.__author__,
    author_email=samsungctl.__author_email__,
    license=samsungctl.__license__,
    long_description=open("README.md").read(),
    entry_points={
        "console_scripts": ["samsungctl=samsungctl.__main__:main"]
    },
    packages=["samsungctl"],
    install_requires=[],
    classifiers=[
        "Development Status :: 4 - Beta",
        "Environment :: Console",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python :: 3",
        "Topic :: Home Automation",
    ],
)

Response:
<REPLACE_OLD> Automation"
 <REPLACE_NEW> Automation",
 <REPLACE_END> <REPLACE_OLD> ]
)
 <REPLACE_NEW> ],
)
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

import setuptools

import samsungctl

setuptools.setup(
    name=samsungctl.__title__,
    version=samsungctl.__version__,
    description=samsungctl.__doc__,
    url=samsungctl.__url__,
    author=samsungctl.__author__,
    author_email=samsungctl.__author_email__,
    license=samsungctl.__license__,
    long_description=open("README.md").read(),
    entry_points={
        "console_scripts": ["samsungctl=samsungctl.__main__:main"]
    },
    packages=["samsungctl"],
    install_requires=[],
    classifiers=[
        "Development Status :: 4 - Beta",
        "Environment :: Console",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python :: 3",
        "Topic :: Home Automation",
    ],
)

Prompt:
Use comma on every line on multi-line lists

#!/usr/bin/env python

import setuptools

import samsungctl

setuptools.setup(
    name=samsungctl.__title__,
    version=samsungctl.__version__,
    description=samsungctl.__doc__,
    url=samsungctl.__url__,
    author=samsungctl.__author__,
    author_email=samsungctl.__author_email__,
    license=samsungctl.__license__,
    long_description=open("README.md").read(),
    entry_points={
        "console_scripts": ["samsungctl=samsungctl.__main__:main"]
    },
    packages=["samsungctl"],
    install_requires=[],
    classifiers=[
        "Development Status :: 4 - Beta",
        "Environment :: Console",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python :: 3",
        "Topic :: Home Automation"
    ]
)


"""
Module with the TestCase model.
"""

from launch_control.utils.json.pod import PlainOldData

class TestCase(PlainOldData):
    """
    TestCase model.

    Currently contains just two fields:
        - test_case_id (test-case specific ID)
        - name (human readable)
    """

    __slots__ = ('test_case_id', 'name')

    def __init__(self, test_case_id, desc):
        self.test_case_id = test_case_id
        self.name = name

Response:
<REPLACE_OLD> 'desc')

 <REPLACE_NEW> 'name')

 <REPLACE_END> <|endoftext|> """
Module with the TestCase model.
"""

from launch_control.utils.json.pod import PlainOldData

class TestCase(PlainOldData):
    """
    TestCase model.

    Currently contains just two fields:
        - test_case_id (test-case specific ID)
        - name (human readable)
    """

    __slots__ = ('test_case_id', 'name')

    def __init__(self, test_case_id, desc):
        self.test_case_id = test_case_id
        self.name = name

Prompt:
Fix TestCase definition to have a slot 'name' instead of 'desc'

"""
Module with the TestCase model.
"""

from launch_control.utils.json.pod import PlainOldData

class TestCase(PlainOldData):
    """
    TestCase model.

    Currently contains just two fields:
        - test_case_id (test-case specific ID)
        - name (human readable)
    """

    __slots__ = ('test_case_id', 'desc')

    def __init__(self, test_case_id, desc):
        self.test_case_id = test_case_id
        self.name = name


# coding: utf-8

from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from registration.signals import user_activated
from django.dispatch import receiver

class UserAccount(models.Model):
    """
    A user account. Used to store any information related to users.
    """
    user = models.OneToOneField(settings.AUTH_USER_MODEL,
                                related_name='account')

    class Meta:
        verbose_name = _('user account')
        verbose_name_plural = _('user accounts')

    def __unicode__(self):
        return u'{}'.format(self.user.username)

@receiver(user_activated)
def registration_completed(sender, user, request, **kwargs):
    account, created = UserAccount.objects.get_or_create(user=user)
    print account, created

Response:
<REPLACE_OLD> accounts')

@receiver(user_activated)
def <REPLACE_NEW> accounts')

    def __unicode__(self):
        return u'{}'.format(self.user.username)

@receiver(user_activated)
def <REPLACE_END> <|endoftext|> # coding: utf-8

from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from registration.signals import user_activated
from django.dispatch import receiver

class UserAccount(models.Model):
    """
    A user account. Used to store any information related to users.
    """
    user = models.OneToOneField(settings.AUTH_USER_MODEL,
                                related_name='account')

    class Meta:
        verbose_name = _('user account')
        verbose_name_plural = _('user accounts')

    def __unicode__(self):
        return u'{}'.format(self.user.username)

@receiver(user_activated)
def registration_completed(sender, user, request, **kwargs):
    account, created = UserAccount.objects.get_or_create(user=user)
    print account, created

Prompt:
Add __unicode__ method to UserAccount model

# coding: utf-8

from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from registration.signals import user_activated
from django.dispatch import receiver

class UserAccount(models.Model):
    """
    A user account. Used to store any information related to users.
    """
    user = models.OneToOneField(settings.AUTH_USER_MODEL,
                                related_name='account')

    class Meta:
        verbose_name = _('user account')
        verbose_name_plural = _('user accounts')

@receiver(user_activated)
def registration_completed(sender, user, request, **kwargs):
    account, created = UserAccount.objects.get_or_create(user=user)
    print account, created


# -*- coding: utf-8 -*-
"""
Always ignore lines with '# noqa'
"""
__version__ = 0.2

try:
    from pep8 import StandardReport, noqa
except ImportError:
    # Try the new (as of 2016-June) pycodestyle package.
    from pycodestyle import StandardReport, noqa

class RespectNoqaReport(StandardReport):

    def error(self, line_number, offset, text, check):
        if len(self.lines) > line_number - 1 and noqa(self.lines[line_number - 1]):
            return
        else:
            return super(RespectNoqaReport, self).error(line_number, offset,
                                                        text, check)

class RespectNoqa(object):
    name = 'flake8-respect-noqa'
    version = __version__

    def __init__(self, *args, **kwargs):
        pass

    @classmethod
    def parse_options(cls, options):
        # The following only works with (flake8 2.4.1) if you run like "flake8 -j 1",
        # or put "jobs = 1" in your [flake8] config.
        # Otherwise, flake8 replaces this reported with it's own.
        # See https://gitlab.com/pycqa/flake8/issues/66
        options.reporter = RespectNoqaReport
        options.report = RespectNoqaReport(options)

Adjust for pep8 package rename.

Response:
<REPLACE_OLD> 0.2

import pep8

class RespectNoqaReport(pep8.StandardReport):

 <REPLACE_NEW> 0.2

try:
    from pep8 import StandardReport, noqa
except ImportError:
    # Try the new (as of 2016-June) pycodestyle package.
    from pycodestyle import StandardReport, noqa

class RespectNoqaReport(StandardReport):

 <REPLACE_END> <REPLACE_OLD> pep8.noqa(self.lines[line_number <REPLACE_NEW> noqa(self.lines[line_number <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
"""
Always ignore lines with '# noqa'
"""
__version__ = 0.2

try:
    from pep8 import StandardReport, noqa
except ImportError:
    # Try the new (as of 2016-June) pycodestyle package.
    from pycodestyle import StandardReport, noqa

class RespectNoqaReport(StandardReport):

    def error(self, line_number, offset, text, check):
        if len(self.lines) > line_number - 1 and noqa(self.lines[line_number - 1]):
            return
        else:
            return super(RespectNoqaReport, self).error(line_number, offset,
                                                        text, check)

class RespectNoqa(object):
    name = 'flake8-respect-noqa'
    version = __version__

    def __init__(self, *args, **kwargs):
        pass

    @classmethod
    def parse_options(cls, options):
        # The following only works with (flake8 2.4.1) if you run like "flake8 -j 1",
        # or put "jobs = 1" in your [flake8] config.
        # Otherwise, flake8 replaces this reported with it's own.
        # See https://gitlab.com/pycqa/flake8/issues/66
        options.reporter = RespectNoqaReport
        options.report = RespectNoqaReport(options)

Prompt:
Adjust for pep8 package rename.

Closes #1

# -*- coding: utf-8 -*-
"""
Always ignore lines with '# noqa'
"""
__version__ = 0.2

import pep8

class RespectNoqaReport(pep8.StandardReport):

    def error(self, line_number, offset, text, check):
        if len(self.lines) > line_number - 1 and pep8.noqa(self.lines[line_number - 1]):
            return
        else:
            return super(RespectNoqaReport, self).error(line_number, offset,
                                                        text, check)

class RespectNoqa(object):
    name = 'flake8-respect-noqa'
    version = __version__

    def __init__(self, *args, **kwargs):
        pass

    @classmethod
    def parse_options(cls, options):
        # The following only works with (flake8 2.4.1) if you run like "flake8 -j 1",
        # or put "jobs = 1" in your [flake8] config.
        # Otherwise, flake8 replaces this reported with it's own.
        # See https://gitlab.com/pycqa/flake8/issues/66
        options.reporter = RespectNoqaReport
        options.report = RespectNoqaReport(options)


#!/usr/bin/env python
import socket

import struct
import sys

def send_to_chrome(message):
    # Write message size.
    sys.stdout.write(struct.pack('I', len(message)))
    # Write the message itself.
    sys.stdout.write(message)
    sys.stdout.flush()

def read_from_chrome():
    text_length_bytes = sys.stdin.read(4)
    if len(text_length_bytes) == 0:
        sys.exit(0)
    # Unpack message length as 4 byte integer.
    text_length = struct.unpack('i', text_length_bytes)[0]
    # Read the text (JSON object) of the message.
    text = sys.stdin.read(text_length).decode('utf-8')
    return text

# sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
# socket_name = '/tmp/cachebrowser.sock'
# sock.connect(socket_name)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('127.0.0.1', 4242))

message = read_from_chrome()
sock.send(message)
sock.send('\n')

# response = ''
# while True:
#     read = sock.recv(1024)
#     if len(read) == 0:
#         break
#     response += read

response = sock.recv(1024)
send_to_chrome(response)

# send_to_chrome("{}")

Change chromhost to use normal sockets

Change chromhost to use normal sockets

Response:
<REPLACE_OLD> text

sock <REPLACE_NEW> text

# sock <REPLACE_END> <REPLACE_OLD> socket.SOCK_STREAM)
socket_name <REPLACE_NEW> socket.SOCK_STREAM)
# socket_name <REPLACE_END> <REPLACE_OLD> '/tmp/cachebrowser.sock'
sock.connect(socket_name)

message <REPLACE_NEW> '/tmp/cachebrowser.sock'
# sock.connect(socket_name)
sock <REPLACE_END> <REPLACE_OLD> read_from_chrome()
sock.send(message)
sock.send('\n')

response <REPLACE_NEW> socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('127.0.0.1', 4242))

message <REPLACE_END> <REPLACE_OLD> ''
while True:
 <REPLACE_NEW> read_from_chrome()
sock.send(message)
sock.send('\n')

# response = ''
# while True:
#  <REPLACE_END> <REPLACE_OLD> sock.recv(1024)
 <REPLACE_NEW> sock.recv(1024)
#  <REPLACE_END> <REPLACE_OLD> 0:
 <REPLACE_NEW> 0:
# <REPLACE_END> <REPLACE_OLD> break
 <REPLACE_NEW>  break
#  <REPLACE_END> <REPLACE_OLD> read
# response <REPLACE_NEW> read

response <REPLACE_END> <REPLACE_OLD> sock.recv(1024)

send_to_chrome(response)

 <REPLACE_NEW> sock.recv(1024)
send_to_chrome(response)

# send_to_chrome("{}")
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
import socket

import struct
import sys

def send_to_chrome(message):
    # Write message size.
    sys.stdout.write(struct.pack('I', len(message)))
    # Write the message itself.
    sys.stdout.write(message)
    sys.stdout.flush()

def read_from_chrome():
    text_length_bytes = sys.stdin.read(4)
    if len(text_length_bytes) == 0:
        sys.exit(0)
    # Unpack message length as 4 byte integer.
    text_length = struct.unpack('i', text_length_bytes)[0]
    # Read the text (JSON object) of the message.
    text = sys.stdin.read(text_length).decode('utf-8')
    return text

# sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
# socket_name = '/tmp/cachebrowser.sock'
# sock.connect(socket_name)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('127.0.0.1', 4242))

message = read_from_chrome()
sock.send(message)
sock.send('\n')

# response = ''
# while True:
#     read = sock.recv(1024)
#     if len(read) == 0:
#         break
#     response += read

response = sock.recv(1024)
send_to_chrome(response)

# send_to_chrome("{}")

Prompt:
Change chromhost to use normal sockets

#!/usr/bin/env python
import socket

import struct
import sys

def send_to_chrome(message):
    # Write message size.
    sys.stdout.write(struct.pack('I', len(message)))
    # Write the message itself.
    sys.stdout.write(message)
    sys.stdout.flush()

def read_from_chrome():
    text_length_bytes = sys.stdin.read(4)
    if len(text_length_bytes) == 0:
        sys.exit(0)
    # Unpack message length as 4 byte integer.
    text_length = struct.unpack('i', text_length_bytes)[0]
    # Read the text (JSON object) of the message.
    text = sys.stdin.read(text_length).decode('utf-8')
    return text

sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
socket_name = '/tmp/cachebrowser.sock'
sock.connect(socket_name)

message = read_from_chrome()
sock.send(message)
sock.send('\n')

response = ''
while True:
    read = sock.recv(1024)
    if len(read) == 0:
        break
    response += read
# response = sock.recv(1024)

send_to_chrome(response)


"""Test file for the ordered dictionary module, odict.py."""

from neuroimaging.externals.scipy.testing import *

from neuroimaging.utils.odict import odict

class TestOdict(TestCase):
    def setUp(self):
        print 'setUp'
        self.thedict = odict((('one', 1.0), ('two', 2.0), ('three', 3.0)))

    def test_copy(self):
        """Test odict.copy method."""
        print self.thedict
        cpydict = self.thedict.copy()
        assert cpydict == self.thedict
        # test that it's a copy and not a reference
        assert cpydict is not self.thedict

if __name__ == "__main__":
    nose.runmodule()

Fix nose call so tests run in __main__.

Response:
<REPLACE_OLD> nose.run(argv=['', __file__])
 <REPLACE_NEW> nose.runmodule()
 <REPLACE_END> <|endoftext|> """Test file for the ordered dictionary module, odict.py."""

from neuroimaging.externals.scipy.testing import *

from neuroimaging.utils.odict import odict

class TestOdict(TestCase):
    def setUp(self):
        print 'setUp'
        self.thedict = odict((('one', 1.0), ('two', 2.0), ('three', 3.0)))

    def test_copy(self):
        """Test odict.copy method."""
        print self.thedict
        cpydict = self.thedict.copy()
        assert cpydict == self.thedict
        # test that it's a copy and not a reference
        assert cpydict is not self.thedict

if __name__ == "__main__":
    nose.runmodule()

Prompt:
BUG: Fix nose call so tests run in __main__.
"""Test file for the ordered dictionary module, odict.py."""

from neuroimaging.externals.scipy.testing import *

from neuroimaging.utils.odict import odict

class TestOdict(TestCase):
    def setUp(self):
        print 'setUp'
        self.thedict = odict((('one', 1.0), ('two', 2.0), ('three', 3.0)))

    def test_copy(self):
        """Test odict.copy method."""
        print self.thedict
        cpydict = self.thedict.copy()
        assert cpydict == self.thedict
        # test that it's a copy and not a reference
        assert cpydict is not self.thedict

if __name__ == "__main__":
    nose.run(argv=['', __file__])


# -*- encoding: utf-8 -*-
import config

from flask import Blueprint
from flask import render_template
from lazyblacksmith.models import Activity
from lazyblacksmith.models import Item
from lazyblacksmith.models import Region

blueprint = Blueprint('blueprint', __name__)

@blueprint.route('/manufacturing/<int:item_id>')
def manufacturing(item_id):
    """
    Display the manufacturing page with all data
    """
    item = Item.query.get(item_id)
    activity = item.activities.filter_by(activity=Activity.ACTIVITY_MANUFACTURING).one()
    materials = item.activity_materials.filter_by(activity=Activity.ACTIVITY_MANUFACTURING)
    product = item.activity_products.filter_by(activity=Activity.ACTIVITY_MANUFACTURING).one()
    regions = Region.query.filter(
        Region.id.in_(config.CREST_REGION_PRICE)
    ).filter_by(
        wh=False
    )

    # is any of the materials manufactured ?
    has_manufactured_components = False

    for material in materials:
        if material.material.is_manufactured():
            has_manufactured_components = True
            break

    return render_template('blueprint/manufacturing.html', **{
        'blueprint': item,
        'materials': materials,
        'activity': activity,
        'product': product,
        'regions': regions,
        'has_manufactured_components': has_manufactured_components,
    })

@blueprint.route('/')
def search():
    return render_template('blueprint/search.html')

Change region list to match config

Change region list to match config

Response:
<REPLACE_OLD> -*-
from <REPLACE_NEW> -*-
import config

from <REPLACE_END> <REPLACE_OLD> render_template

from <REPLACE_NEW> render_template
from <REPLACE_END> <REPLACE_OLD> Region.query.filter_by(wh=False)

 <REPLACE_NEW> Region.query.filter(
        Region.id.in_(config.CREST_REGION_PRICE)
    ).filter_by(
        wh=False
    )

 <REPLACE_END> <|endoftext|> # -*- encoding: utf-8 -*-
import config

from flask import Blueprint
from flask import render_template
from lazyblacksmith.models import Activity
from lazyblacksmith.models import Item
from lazyblacksmith.models import Region

blueprint = Blueprint('blueprint', __name__)

@blueprint.route('/manufacturing/<int:item_id>')
def manufacturing(item_id):
    """
    Display the manufacturing page with all data
    """
    item = Item.query.get(item_id)
    activity = item.activities.filter_by(activity=Activity.ACTIVITY_MANUFACTURING).one()
    materials = item.activity_materials.filter_by(activity=Activity.ACTIVITY_MANUFACTURING)
    product = item.activity_products.filter_by(activity=Activity.ACTIVITY_MANUFACTURING).one()
    regions = Region.query.filter(
        Region.id.in_(config.CREST_REGION_PRICE)
    ).filter_by(
        wh=False
    )

    # is any of the materials manufactured ?
    has_manufactured_components = False

    for material in materials:
        if material.material.is_manufactured():
            has_manufactured_components = True
            break

    return render_template('blueprint/manufacturing.html', **{
        'blueprint': item,
        'materials': materials,
        'activity': activity,
        'product': product,
        'regions': regions,
        'has_manufactured_components': has_manufactured_components,
    })

@blueprint.route('/')
def search():
    return render_template('blueprint/search.html')

Prompt:
Change region list to match config

# -*- encoding: utf-8 -*-
from flask import Blueprint
from flask import render_template

from lazyblacksmith.models import Activity
from lazyblacksmith.models import Item
from lazyblacksmith.models import Region

blueprint = Blueprint('blueprint', __name__)

@blueprint.route('/manufacturing/<int:item_id>')
def manufacturing(item_id):
    """
    Display the manufacturing page with all data
    """
    item = Item.query.get(item_id)
    activity = item.activities.filter_by(activity=Activity.ACTIVITY_MANUFACTURING).one()
    materials = item.activity_materials.filter_by(activity=Activity.ACTIVITY_MANUFACTURING)
    product = item.activity_products.filter_by(activity=Activity.ACTIVITY_MANUFACTURING).one()
    regions = Region.query.filter_by(wh=False)

    # is any of the materials manufactured ?
    has_manufactured_components = False

    for material in materials:
        if material.material.is_manufactured():
            has_manufactured_components = True
            break

    return render_template('blueprint/manufacturing.html', **{
        'blueprint': item,
        'materials': materials,
        'activity': activity,
        'product': product,
        'regions': regions,
        'has_manufactured_components': has_manufactured_components,
    })

@blueprint.route('/')
def search():
    return render_template('blueprint/search.html')


# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.

from . import SimpleView

from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")

def getMetaData():
    return {
        "type": "view",
        "plugin": {
            "name": i18n_catalog.i18nc("@label", "Simple View"),
            "author": "Ultimaker",
            "version": "1.0",
            "description": i18n_catalog.i18nc("@info:whatsthis", "Provides a simple solid mesh view."),
            "api": 2
        },
        "view": {
            "name": i18n_catalog.i18nc("@item:inmenu", "Simple"),
            "visible": False
        }
    }

def register(app):
    return { "view": SimpleView.SimpleView() }

Fix plug-in type and description key

Response:
<INSERT>        "type": "view",
 <INSERT_END> <REPLACE_OLD> "decription": <REPLACE_NEW> "description": <REPLACE_END> <|endoftext|> # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.

from . import SimpleView

from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")

def getMetaData():
    return {
        "type": "view",
        "plugin": {
            "name": i18n_catalog.i18nc("@label", "Simple View"),
            "author": "Ultimaker",
            "version": "1.0",
            "description": i18n_catalog.i18nc("@info:whatsthis", "Provides a simple solid mesh view."),
            "api": 2
        },
        "view": {
            "name": i18n_catalog.i18nc("@item:inmenu", "Simple"),
            "visible": False
        }
    }

def register(app):
    return { "view": SimpleView.SimpleView() }

Prompt:
Fix plug-in type and description key

't Was a typo.

Contributes to issue CURA-1190.

# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.

from . import SimpleView

from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")

def getMetaData():
    return {
        "plugin": {
            "name": i18n_catalog.i18nc("@label", "Simple View"),
            "author": "Ultimaker",
            "version": "1.0",
            "decription": i18n_catalog.i18nc("@info:whatsthis", "Provides a simple solid mesh view."),
            "api": 2
        },
        "view": {
            "name": i18n_catalog.i18nc("@item:inmenu", "Simple"),
            "visible": False
        }
    }

def register(app):
    return { "view": SimpleView.SimpleView() }


# Copyright (c) 2015 Ansible, Inc..
# All Rights Reserved.

import json
from django.conf import settings as django_settings
from awx.main.models.configuration import TowerSettings

class TowerConfiguration(object):

    # TODO: Caching so we don't have to hit the database every time for settings
    def __getattr__(self, key):
        ts = TowerSettings.objects.filter(key=key)
        if not ts.exists():
            return getattr(django_settings, key)
        return ts[0].value_converted

    def create(key, value):
        settings_manifest = django_settings.TOWER_SETTINGS_MANIFEST
        if key not in settings_manifest:
            raise AttributeError("Tower Setting with key '{0}' does not exist".format(key))
        settings_entry = settings_manifest[key]
        setting_actual = TowerSettings.objects.filter(key=key)
        if not settings_actual.exists():
            settings_actual = TowerSettings(key=key,
                                            description=settings_entry['description'],
                                            category=settings_entry['category'],
                                            value=value,
                                            value_type=settings_entry['type'])
        else:
            settings_actual['value'] = value
        settings_actual.save()

tower_settings = TowerConfiguration()

Add a note about caching

Add a note about caching

Response:
<INSERT> # TODO: Caching so we don't have to hit the database every time for settings
    <INSERT_END> <|endoftext|> # Copyright (c) 2015 Ansible, Inc..
# All Rights Reserved.

import json
from django.conf import settings as django_settings
from awx.main.models.configuration import TowerSettings

class TowerConfiguration(object):

    # TODO: Caching so we don't have to hit the database every time for settings
    def __getattr__(self, key):
        ts = TowerSettings.objects.filter(key=key)
        if not ts.exists():
            return getattr(django_settings, key)
        return ts[0].value_converted

    def create(key, value):
        settings_manifest = django_settings.TOWER_SETTINGS_MANIFEST
        if key not in settings_manifest:
            raise AttributeError("Tower Setting with key '{0}' does not exist".format(key))
        settings_entry = settings_manifest[key]
        setting_actual = TowerSettings.objects.filter(key=key)
        if not settings_actual.exists():
            settings_actual = TowerSettings(key=key,
                                            description=settings_entry['description'],
                                            category=settings_entry['category'],
                                            value=value,
                                            value_type=settings_entry['type'])
        else:
            settings_actual['value'] = value
        settings_actual.save()

tower_settings = TowerConfiguration()

Prompt:
Add a note about caching

# Copyright (c) 2015 Ansible, Inc..
# All Rights Reserved.

import json
from django.conf import settings as django_settings
from awx.main.models.configuration import TowerSettings

class TowerConfiguration(object):

    def __getattr__(self, key):
        ts = TowerSettings.objects.filter(key=key)
        if not ts.exists():
            return getattr(django_settings, key)
        return ts[0].value_converted

    def create(key, value):
        settings_manifest = django_settings.TOWER_SETTINGS_MANIFEST
        if key not in settings_manifest:
            raise AttributeError("Tower Setting with key '{0}' does not exist".format(key))
        settings_entry = settings_manifest[key]
        setting_actual = TowerSettings.objects.filter(key=key)
        if not settings_actual.exists():
            settings_actual = TowerSettings(key=key,
                                            description=settings_entry['description'],
                                            category=settings_entry['category'],
                                            value=value,
                                            value_type=settings_entry['type'])
        else:
            settings_actual['value'] = value
        settings_actual.save()

tower_settings = TowerConfiguration()


# Run the following command to test:
#
#     (in /usr/local/googkit)
#     $ python -m {test_module_name}
#
# See also: http://docs.python.org/3.3/library/unittest.html#command-line-interface
#
# We cannot use unittest.mock on python 2.x!
# Please install the Mock module when you use Python 2.x.
#
#     $ easy_install -U Mock
#
# See also: http://www.voidspace.org.uk/python/mock/#installing

import unittest
import os

try:
    # Python 3.3 or later
    import unittest.mock as mock
except ImportError:
    # Python 2.x or 3.2-
    import mock

from lib.environment import Environment

class TestEnvironmtnt(unittest.TestCase):
    # run {{{
    def test_init(self):
        args = mock.MagicMock()
        config = mock.MagicMock()

        env = Environment(args, config)

        self.assertEqual(env.args, args)
        self.assertEqual(env.config, config)
    # }}}

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

# vim: fdm=marker

Add a test for lib.environment

Add a test for lib.environment

Response:
<INSERT> # Run the following command to test:
#
# <INSERT_END> <INSERT>    (in /usr/local/googkit)
#     $ python -m {test_module_name}
#
# See also: http://docs.python.org/3.3/library/unittest.html#command-line-interface
#
# We cannot use unittest.mock on python 2.x!
# Please install the Mock module when you use Python 2.x.
#
#     $ easy_install -U Mock
#
# See also: http://www.voidspace.org.uk/python/mock/#installing

import unittest
import os

try:
    # Python 3.3 or later
    import unittest.mock as mock
except ImportError:
    # Python 2.x or 3.2-
    import mock

from lib.environment import Environment

class TestEnvironmtnt(unittest.TestCase):
    # run {{{
    def test_init(self):
        args = mock.MagicMock()
        config = mock.MagicMock()

        env = Environment(args, config)

        self.assertEqual(env.args, args)
        self.assertEqual(env.config, config)
    # }}}

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

# vim: fdm=marker
 <INSERT_END> <|endoftext|> # Run the following command to test:
#
#     (in /usr/local/googkit)
#     $ python -m {test_module_name}
#
# See also: http://docs.python.org/3.3/library/unittest.html#command-line-interface
#
# We cannot use unittest.mock on python 2.x!
# Please install the Mock module when you use Python 2.x.
#
#     $ easy_install -U Mock
#
# See also: http://www.voidspace.org.uk/python/mock/#installing

import unittest
import os

try:
    # Python 3.3 or later
    import unittest.mock as mock
except ImportError:
    # Python 2.x or 3.2-
    import mock

from lib.environment import Environment

class TestEnvironmtnt(unittest.TestCase):
    # run {{{
    def test_init(self):
        args = mock.MagicMock()
        config = mock.MagicMock()

        env = Environment(args, config)

        self.assertEqual(env.args, args)
        self.assertEqual(env.config, config)
    # }}}

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

# vim: fdm=marker

Prompt: Add a test for lib.environment


# -*- coding: utf-8 -*-
from django.contrib import admin
from powerdns.models import Domain, Record, Supermaster

class RecordAdmin(admin.ModelAdmin):
    list_display = ('name', 'type', 'content', 'ttl', 'prio', 'change_date',)
    list_filter = ['type', 'ttl',]
    search_fields  = ('name','content',)
    readonly_fields = ('change_date',)

class DomainAdmin(admin.ModelAdmin):
    list_display = ('name', 'type', 'last_check', 'account',)
    list_filter = ['type', 'last_check', 'account',]
    search_fields  = ('name',)
    readonly_fields = ('notified_serial',)

class SupermasterAdmin(admin.ModelAdmin):
    list_display = ('ip', 'nameserver', 'account',)
    list_filter = ['ip', 'account',]
    search_fields  = ('ip', 'nameserver',)

admin.site.register(Domain,DomainAdmin)
admin.site.register(Record,RecordAdmin)
admin.site.register(Supermaster,SupermasterAdmin)

Response:
<REPLACE_OLD> ('name','content',)

class <REPLACE_NEW> ('name','content',)
    readonly_fields = ('change_date',)

class <REPLACE_END> <REPLACE_OLD> ('name',)

class <REPLACE_NEW> ('name',)
    readonly_fields = ('notified_serial',)

class <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from django.contrib import admin
from powerdns.models import Domain, Record, Supermaster

class RecordAdmin(admin.ModelAdmin):
    list_display = ('name', 'type', 'content', 'ttl', 'prio', 'change_date',)
    list_filter = ['type', 'ttl',]
    search_fields  = ('name','content',)
    readonly_fields = ('change_date',)

class DomainAdmin(admin.ModelAdmin):
    list_display = ('name', 'type', 'last_check', 'account',)
    list_filter = ['type', 'last_check', 'account',]
    search_fields  = ('name',)
    readonly_fields = ('notified_serial',)

class SupermasterAdmin(admin.ModelAdmin):
    list_display = ('ip', 'nameserver', 'account',)
    list_filter = ['ip', 'account',]
    search_fields  = ('ip', 'nameserver',)

admin.site.register(Domain,DomainAdmin)
admin.site.register(Record,RecordAdmin)
admin.site.register(Supermaster,SupermasterAdmin)

Prompt:
Mark some fields as readonly in the Admin panel as they are set by the server (Requires Django 1.2 or greater)

# -*- coding: utf-8 -*-
from django.contrib import admin
from powerdns.models import Domain, Record, Supermaster

class RecordAdmin(admin.ModelAdmin):
    list_display = ('name', 'type', 'content', 'ttl', 'prio', 'change_date',)
    list_filter = ['type', 'ttl',]
    search_fields  = ('name','content',)

class DomainAdmin(admin.ModelAdmin):
    list_display = ('name', 'type', 'last_check', 'account',)
    list_filter = ['type', 'last_check', 'account',]
    search_fields  = ('name',)

class SupermasterAdmin(admin.ModelAdmin):
    list_display = ('ip', 'nameserver', 'account',)
    list_filter = ['ip', 'account',]
    search_fields  = ('ip', 'nameserver',)

admin.site.register(Domain,DomainAdmin)
admin.site.register(Record,RecordAdmin)
admin.site.register(Supermaster,SupermasterAdmin)


import pytest

from thinglang.runner import run

def test_simple_conditionals():
    assert run("""
thing Program
    does start
        if "dog" eq "dog"
            Output.write("dog is dog")

        if "dog" eq "cat"
            Output.write("dog is cat")

    """).output == """dog is dog""".strip()

def test_unconditional_else():
    assert run("""
thing Program
    does start
        if "dog" eq "dog"
            Output.write("dog is dog")
        otherwise
            Output.write("dog is not dog")

        if "dog" eq "cat"
            Output.write("dog is cat")
        otherwise
            Output.write("dog is not cat")
    """).output == """dog is dog\ndog is not cat""".strip()

def test_conditional_else():
    assert run("""
thing Program
    does start
        if "dog" eq "cat"
            Output.write("dog is cat")
        otherwise if "dog" eq "dog"
            Output.write("dog is dog")
        otherwise if "dog" eq "dog"
            Output.write("dog is still dog")
        otherwise
            Output.write("dog is not dog and not cat")

        if "dog" eq "cat"
            Output.write("dog is cat")
        otherwise if "dog" eq "Dog"
            Output.write("dog is Dog")
        otherwise if "dog" eq "mouse"
            Output.write("dog is mouse")
        otherwise
            Output.write("dog is not cat and not mouse and not Dog")
    """).output == """dog is dog\ndog is not cat and not mouse and not Dog""".strip()

Update conditional else branch tests

Update conditional else branch tests

Response:
<INSERT> otherwise if "dog" eq "dog"
            Output.write("dog is still dog")
        <INSERT_END> <INSERT> cat")

        if "dog" eq "cat"
            Output.write("dog is <INSERT_END> <INSERT>        otherwise if "dog" eq "Dog"
            Output.write("dog is Dog")
        otherwise if "dog" eq "mouse"
            Output.write("dog is mouse")
        otherwise
            Output.write("dog is not cat and not mouse and not Dog")
 <INSERT_END> <REPLACE_OLD> cat""".strip()
 <REPLACE_NEW> cat and not mouse and not Dog""".strip()
 <REPLACE_END> <|endoftext|> import pytest

from thinglang.runner import run

def test_simple_conditionals():
    assert run("""
thing Program
    does start
        if "dog" eq "dog"
            Output.write("dog is dog")

        if "dog" eq "cat"
            Output.write("dog is cat")

    """).output == """dog is dog""".strip()

def test_unconditional_else():
    assert run("""
thing Program
    does start
        if "dog" eq "dog"
            Output.write("dog is dog")
        otherwise
            Output.write("dog is not dog")

        if "dog" eq "cat"
            Output.write("dog is cat")
        otherwise
            Output.write("dog is not cat")
    """).output == """dog is dog\ndog is not cat""".strip()

def test_conditional_else():
    assert run("""
thing Program
    does start
        if "dog" eq "cat"
            Output.write("dog is cat")
        otherwise if "dog" eq "dog"
            Output.write("dog is dog")
        otherwise if "dog" eq "dog"
            Output.write("dog is still dog")
        otherwise
            Output.write("dog is not dog and not cat")

        if "dog" eq "cat"
            Output.write("dog is cat")
        otherwise if "dog" eq "Dog"
            Output.write("dog is Dog")
        otherwise if "dog" eq "mouse"
            Output.write("dog is mouse")
        otherwise
            Output.write("dog is not cat and not mouse and not Dog")
    """).output == """dog is dog\ndog is not cat and not mouse and not Dog""".strip()

Prompt:
Update conditional else branch tests

import pytest

from thinglang.runner import run

def test_simple_conditionals():
    assert run("""
thing Program
    does start
        if "dog" eq "dog"
            Output.write("dog is dog")

        if "dog" eq "cat"
            Output.write("dog is cat")

    """).output == """dog is dog""".strip()

def test_unconditional_else():
    assert run("""
thing Program
    does start
        if "dog" eq "dog"
            Output.write("dog is dog")
        otherwise
            Output.write("dog is not dog")

        if "dog" eq "cat"
            Output.write("dog is cat")
        otherwise
            Output.write("dog is not cat")
    """).output == """dog is dog\ndog is not cat""".strip()

def test_conditional_else():
    assert run("""
thing Program
    does start
        if "dog" eq "cat"
            Output.write("dog is cat")
        otherwise if "dog" eq "dog"
            Output.write("dog is dog")
        otherwise
            Output.write("dog is not dog and not cat")
    """).output == """dog is dog\ndog is not cat""".strip()


"""
Debug Blueprints.
"""
from flask import Blueprint, current_app, redirect, jsonify, url_for, request

debug_pages = Blueprint('debug', __name__)

@debug_pages.route("/clear_all", methods=['GET', 'POST'])
def clear_all():
    if request.method == 'GET':
        return '<form method="POST"><input type="submit" value="CLEAR DATABASE"></form>'
    else:
        mongo = current_app.mongo
        mongo.db.userSessions.remove()
        mongo.db.interactionSessions.remove()
        return redirect(url_for('destroy_session'))

@debug_pages.route("/dump")
def dump_session():
    mongo = current_app.mongo
    return jsonify({
        'userSessions': list(mongo.db.userSessions.find()),
        'interactionSessions': list(mongo.db.interactionSessions.find()),
    })

Response:
<REPLACE_OLD> url_for

debug_pages <REPLACE_NEW> url_for, request

debug_pages <REPLACE_END> <REPLACE_OLD> __name__)

@debug_pages.route("/clear_all")
def <REPLACE_NEW> __name__)

@debug_pages.route("/clear_all", methods=['GET', 'POST'])
def <REPLACE_END> <INSERT>    if request.method == 'GET':
        return '<form method="POST"><input type="submit" value="CLEAR DATABASE"></form>'
    else:
     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <INSERT>     <INSERT_END> <|endoftext|> """
Debug Blueprints.
"""
from flask import Blueprint, current_app, redirect, jsonify, url_for, request

debug_pages = Blueprint('debug', __name__)

@debug_pages.route("/clear_all", methods=['GET', 'POST'])
def clear_all():
    if request.method == 'GET':
        return '<form method="POST"><input type="submit" value="CLEAR DATABASE"></form>'
    else:
        mongo = current_app.mongo
        mongo.db.userSessions.remove()
        mongo.db.interactionSessions.remove()
        return redirect(url_for('destroy_session'))

@debug_pages.route("/dump")
def dump_session():
    mongo = current_app.mongo
    return jsonify({
        'userSessions': list(mongo.db.userSessions.find()),
        'interactionSessions': list(mongo.db.interactionSessions.find()),
    })

Prompt:
Make it harder to accidentally empty the database

"""
Debug Blueprints.
"""
from flask import Blueprint, current_app, redirect, jsonify, url_for

debug_pages = Blueprint('debug', __name__)

@debug_pages.route("/clear_all")
def clear_all():
    mongo = current_app.mongo
    mongo.db.userSessions.remove()
    mongo.db.interactionSessions.remove()
    return redirect(url_for('destroy_session'))

@debug_pages.route("/dump")
def dump_session():
    mongo = current_app.mongo
    return jsonify({
        'userSessions': list(mongo.db.userSessions.find()),
        'interactionSessions': list(mongo.db.interactionSessions.find()),
    })


# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.

from typing import Any

from iopath.common.file_io import PathHandler, TabularIO

class TabularUriParser:
    def parse_uri(self, uri: str) -> None:
        pass

class TabularPathHandler(PathHandler):
    def _opent(
        self, path: str, mode: str = "r", buffering: int = 32, **kwargs: Any
    ) -> TabularIO:
        assert mode == "r"

Response:
<REPLACE_OLD> Any, Iterable

from <REPLACE_NEW> Any

from <REPLACE_END> <REPLACE_OLD> PathHandler

class <REPLACE_NEW> PathHandler, TabularIO

class <REPLACE_END> <REPLACE_OLD> Iterable[Any]:
 <REPLACE_NEW> TabularIO:
 <REPLACE_END> <|endoftext|> # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.

from typing import Any

from iopath.common.file_io import PathHandler, TabularIO

class TabularUriParser:
    def parse_uri(self, uri: str) -> None:
        pass

class TabularPathHandler(PathHandler):
    def _opent(
        self, path: str, mode: str = "r", buffering: int = 32, **kwargs: Any
    ) -> TabularIO:
        assert mode == "r"

Prompt:
Update type signature of AIRStorePathHandler.opent()

Summary:
The previous diff updated the type signature of the
`PathHandler.opent()` method to return a custom context manager. Here,
we update the return type of the overriden `AIRStorePathHandler.opent()`
method to return an implementation of the `PathHandlerContext` protocol,
namely the `AIRStoreRowDataLoader` instead of `Iterable[Any]` to allow
Pyre to carry out static type checking.

Reviewed By: mackorone

Differential Revision: D33833561

fbshipit-source-id: f642110645b147a955f4375fc24d4c29cdca6f26

# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.

from typing import Any, Iterable

from iopath.common.file_io import PathHandler

class TabularUriParser:
    def parse_uri(self, uri: str) -> None:
        pass

class TabularPathHandler(PathHandler):
    def _opent(
        self, path: str, mode: str = "r", buffering: int = 32, **kwargs: Any
    ) -> Iterable[Any]:
        assert mode == "r"


import shutil

import pytest
try:
    import six
except ImportError:
    from django.utils import six
from django.conf import settings

def teardown_assets_directory():
    # Removing the temporary TEMP_DIR. Ensure we pass in unicode
    # so that it will successfully remove temp trees containing
    # non-ASCII filenames on Windows. (We're assuming the temp dir
    # name itself does not contain non-ASCII characters.)
    shutil.rmtree(six.text_type(settings.TEMP_DIR))

@pytest.fixture(scope="session", autouse=True)
def assets_directory(request):
    request.addfinalizer(teardown_assets_directory)

def get_collect_ignore():
    mapping = {
        'widgy.contrib.widgy_mezzanine': ['widgy/contrib/widgy_mezzanine/'],
        'widgy.contrib.form_builder': ['widgy/contrib/form_builder/'],
        'widgy.contrib.page_builder': ['widgy/contrib/page_builder/'],
        'widgy.contrib.urlconf_include': ['widgy/contrib/urlconf_include/'],
        'widgy.contrib.widgy_i18n': ['widgy/contrib/urlconf_include/'],
    }

    acc = []
    for app, path_list in mapping.items():
        if app not in settings.INSTALLED_APPS:
            acc.extend(path_list)
    return acc

collect_ignore = get_collect_ignore()

Response:
<REPLACE_OLD> request.addfinalizer(teardown_assets_directory)
 <REPLACE_NEW> request.addfinalizer(teardown_assets_directory)

def get_collect_ignore():
    mapping = {
        'widgy.contrib.widgy_mezzanine': ['widgy/contrib/widgy_mezzanine/'],
        'widgy.contrib.form_builder': ['widgy/contrib/form_builder/'],
        'widgy.contrib.page_builder': ['widgy/contrib/page_builder/'],
        'widgy.contrib.urlconf_include': ['widgy/contrib/urlconf_include/'],
        'widgy.contrib.widgy_i18n': ['widgy/contrib/urlconf_include/'],
    }

    acc = []
    for app, path_list in mapping.items():
        if app not in settings.INSTALLED_APPS:
            acc.extend(path_list)
    return acc

collect_ignore = get_collect_ignore()
 <REPLACE_END> <|endoftext|> import shutil

import pytest
try:
    import six
except ImportError:
    from django.utils import six
from django.conf import settings

def teardown_assets_directory():
    # Removing the temporary TEMP_DIR. Ensure we pass in unicode
    # so that it will successfully remove temp trees containing
    # non-ASCII filenames on Windows. (We're assuming the temp dir
    # name itself does not contain non-ASCII characters.)
    shutil.rmtree(six.text_type(settings.TEMP_DIR))

@pytest.fixture(scope="session", autouse=True)
def assets_directory(request):
    request.addfinalizer(teardown_assets_directory)

def get_collect_ignore():
    mapping = {
        'widgy.contrib.widgy_mezzanine': ['widgy/contrib/widgy_mezzanine/'],
        'widgy.contrib.form_builder': ['widgy/contrib/form_builder/'],
        'widgy.contrib.page_builder': ['widgy/contrib/page_builder/'],
        'widgy.contrib.urlconf_include': ['widgy/contrib/urlconf_include/'],
        'widgy.contrib.widgy_i18n': ['widgy/contrib/urlconf_include/'],
    }

    acc = []
    for app, path_list in mapping.items():
        if app not in settings.INSTALLED_APPS:
            acc.extend(path_list)
    return acc

collect_ignore = get_collect_ignore()

Prompt:
Make pytest autodiscover tests depending on the INSTALLED_APPS

import shutil

import pytest
try:
    import six
except ImportError:
    from django.utils import six
from django.conf import settings

def teardown_assets_directory():
    # Removing the temporary TEMP_DIR. Ensure we pass in unicode
    # so that it will successfully remove temp trees containing
    # non-ASCII filenames on Windows. (We're assuming the temp dir
    # name itself does not contain non-ASCII characters.)
    shutil.rmtree(six.text_type(settings.TEMP_DIR))

@pytest.fixture(scope="session", autouse=True)
def assets_directory(request):
    request.addfinalizer(teardown_assets_directory)


from nose.tools import ok_, eq_
from pennathletics.athletes import get_roster, get_player

class TestAthletics():
    def test_roster(self):
        ok_(get_roster("m-baskbl", 2015) != [])

    def test_player_empty(self):
        ok_(get_player("m-baskbl", 2014) != [])

    def test_player_number(self):
        eq_(get_player("m-baskbl", 2013, jersey=1)[0].height, "6'2\"")

    def test_player_hometown(self):
        player = get_player("m-baskbl", 2012, homeTown="Belfast, Ireland")[0]
        eq_(player.weight, '210 lbs')

    def test_player_softball(self):
        # 19 players on the 2013 softball team
        eq_(len(get_roster("w-softbl", 2013)), 19)

Add a few more tests for variety

Add a few more tests for variety

Response:
<REPLACE_OLD> "6'2\"")
 <REPLACE_NEW> "6'2\"")

    def test_player_hometown(self):
        player = get_player("m-baskbl", 2012, homeTown="Belfast, Ireland")[0]
        eq_(player.weight, '210 lbs')

    def test_player_softball(self):
        # 19 players on the 2013 softball team
        eq_(len(get_roster("w-softbl", 2013)), 19)
 <REPLACE_END> <|endoftext|> from nose.tools import ok_, eq_
from pennathletics.athletes import get_roster, get_player

class TestAthletics():
    def test_roster(self):
        ok_(get_roster("m-baskbl", 2015) != [])

    def test_player_empty(self):
        ok_(get_player("m-baskbl", 2014) != [])

    def test_player_number(self):
        eq_(get_player("m-baskbl", 2013, jersey=1)[0].height, "6'2\"")

    def test_player_hometown(self):
        player = get_player("m-baskbl", 2012, homeTown="Belfast, Ireland")[0]
        eq_(player.weight, '210 lbs')

    def test_player_softball(self):
        # 19 players on the 2013 softball team
        eq_(len(get_roster("w-softbl", 2013)), 19)

Prompt:
Add a few more tests for variety

from nose.tools import ok_, eq_
from pennathletics.athletes import get_roster, get_player

class TestAthletics():
    def test_roster(self):
        ok_(get_roster("m-baskbl", 2015) != [])

    def test_player_empty(self):
        ok_(get_player("m-baskbl", 2014) != [])

    def test_player_number(self):
        eq_(get_player("m-baskbl", 2013, jersey=1)[0].height, "6'2\"")


from decimal import Decimal

from cryptex.transaction import Deposit, Withdrawal
from cryptex.trade import Buy, Sell
from functools import partial

class PLCalculator(object):
    def __init__(self, exchange):
        self.exchange = exchange

    @staticmethod
    def convert_transaction(market, tx):
        """
        Convert to buy orders or sell trades of 0 cost and 0 price
        """
        base, counter = market
        if isinstance(tx, Deposit):
            trade_cls = Buy
        else:
            trade_cls = Sell

        return trade_cls(None, base, counter, tx.datetime, None,
                         tx.amount, Decimal('0'))

    def _get_trades(self, market):
        """
        Returns all trades in a particular market along with
        transaction of the base currency, sorted by time.
        """
        base, counter = market
        trades = [t for t in self.exchange.get_my_trades()
                  if t.base_currency == base and
                  t.counter_currency == counter]
        txs = [t for t in self.exchange.get_my_transactions()
               if t.currency == base]
        tx_trades = map(partial(PLCalculator.convert_transaction, market), txs)

        all_trades = sorted(trades + tx_trades, key=lambda x: x.datetime)
        return all_trades

    def unrealized_pl(self, market):
        base, counter = market
        trades = self._get_trades(market)

        def merge_trades(acc, trade):
            if isinstance(trade, Buy):
                new_trade = Buy(None, base, counter, trade.datetime, None,
                                trade.amount, trade.price)
                acc.append(new_trade)
            else:
                oldest_buy = None
                total_amount = Decimal('0')
                while total_amount < trade.amount:
                    oldest_buy = acc.pop()
                    total_amount += oldest_buy.amount
                buy_amount = trade.amount - total_amount
                if buy_amount != Decimal('0'):
                    new_trade = Buy(None, base, counter, oldest_buy.datetime,
                                    None, buy_amount, oldest_buy.price)
                    acc.append(new_trade)
            return acc

        return reduce(merge_trades, trades, [])

Add PL Calculator for unrealized profit and loss calculation

Response:
<REPLACE_OLD>  <REPLACE_NEW> from decimal import Decimal

from cryptex.transaction import Deposit, Withdrawal
from cryptex.trade import Buy, Sell
from functools import partial

class PLCalculator(object):
    def __init__(self, exchange):
        self.exchange = exchange

    @staticmethod
    def convert_transaction(market, tx):
        """
        Convert to buy orders or sell trades of 0 cost and 0 price
        """
        base, counter = market
        if isinstance(tx, Deposit):
            trade_cls = Buy
        else:
            trade_cls = Sell

        return trade_cls(None, base, counter, tx.datetime, None,
                         tx.amount, Decimal('0'))

    def _get_trades(self, market):
        """
        Returns all trades in a particular market along with
        transaction of the base currency, sorted by time.
        """
        base, counter = market
        trades = [t for t in self.exchange.get_my_trades()
                  if t.base_currency == base and
                  t.counter_currency == counter]
        txs = [t for t in self.exchange.get_my_transactions()
               if t.currency == base]
        tx_trades = map(partial(PLCalculator.convert_transaction, market), txs)

        all_trades = sorted(trades + tx_trades, key=lambda x: x.datetime)
        return all_trades

    def unrealized_pl(self, market):
        base, counter = market
        trades = self._get_trades(market)

        def merge_trades(acc, trade):
            if isinstance(trade, Buy):
                new_trade = Buy(None, base, counter, trade.datetime, None,
                                trade.amount, trade.price)
                acc.append(new_trade)
            else:
                oldest_buy = None
                total_amount = Decimal('0')
                while total_amount < trade.amount:
                    oldest_buy = acc.pop()
                    total_amount += oldest_buy.amount
                buy_amount = trade.amount - total_amount
                if buy_amount != Decimal('0'):
                    new_trade = Buy(None, base, counter, oldest_buy.datetime,
                                    None, buy_amount, oldest_buy.price)
                    acc.append(new_trade)
            return acc

        return reduce(merge_trades, trades, [])
 <REPLACE_END> <|endoftext|> from decimal import Decimal

from cryptex.transaction import Deposit, Withdrawal
from cryptex.trade import Buy, Sell
from functools import partial

class PLCalculator(object):
    def __init__(self, exchange):
        self.exchange = exchange

    @staticmethod
    def convert_transaction(market, tx):
        """
        Convert to buy orders or sell trades of 0 cost and 0 price
        """
        base, counter = market
        if isinstance(tx, Deposit):
            trade_cls = Buy
        else:
            trade_cls = Sell

        return trade_cls(None, base, counter, tx.datetime, None,
                         tx.amount, Decimal('0'))

    def _get_trades(self, market):
        """
        Returns all trades in a particular market along with
        transaction of the base currency, sorted by time.
        """
        base, counter = market
        trades = [t for t in self.exchange.get_my_trades()
                  if t.base_currency == base and
                  t.counter_currency == counter]
        txs = [t for t in self.exchange.get_my_transactions()
               if t.currency == base]
        tx_trades = map(partial(PLCalculator.convert_transaction, market), txs)

        all_trades = sorted(trades + tx_trades, key=lambda x: x.datetime)
        return all_trades

    def unrealized_pl(self, market):
        base, counter = market
        trades = self._get_trades(market)

        def merge_trades(acc, trade):
            if isinstance(trade, Buy):
                new_trade = Buy(None, base, counter, trade.datetime, None,
                                trade.amount, trade.price)
                acc.append(new_trade)
            else:
                oldest_buy = None
                total_amount = Decimal('0')
                while total_amount < trade.amount:
                    oldest_buy = acc.pop()
                    total_amount += oldest_buy.amount
                buy_amount = trade.amount - total_amount
                if buy_amount != Decimal('0'):
                    new_trade = Buy(None, base, counter, oldest_buy.datetime,
                                    None, buy_amount, oldest_buy.price)
                    acc.append(new_trade)
            return acc

        return reduce(merge_trades, trades, [])

Prompt: Add PL Calculator for unrealized profit and loss calculation


# -*- coding:utf-8 -*-
from flask import g, jsonify

from gather.api import need_auth, EXCLUDE_COLUMNS

from gather.extensions import api_manager
from gather.topic.models import Topic, Reply

bp = api_manager.create_api_blueprint(
    Topic,
    methods=["GET", "POST"],
    preprocessors={
        'POST': [need_auth],
    },
    include_methods=["have_read"],
    exclude_columns=EXCLUDE_COLUMNS
)

@bp.route("/topic/<int:topic_id>/mark_read")
def _mark_read_for_topic(topic_id):
    need_auth()
    topic = Topic.query.get_or_404(topic_id)
    topic.mark_read(g.token_user)
    return jsonify({"code": 200})

def _update_topic_updated(result=None, **kw):
    if not result:
        return
    reply = Reply.query.get(result["id"])
    reply.topic.updated = reply.created
    reply.topic.clear_read()
    reply.topic.save()

reply_bp = api_manager.create_api_blueprint(
    Reply,
    methods=["POST"],
    preprocessors={
        'POST': [need_auth],
    },
    postprocessors={
        'POST': [_update_topic_updated]
    },
    exclude_columns=EXCLUDE_COLUMNS
)

Add API to mark topic as reader

Add API to mark topic as reader

Response:
<REPLACE_OLD> -*-

from <REPLACE_NEW> -*-
from flask import g, jsonify

from <REPLACE_END> <REPLACE_OLD> exclude_columns=EXCLUDE_COLUMNS
)

def <REPLACE_NEW> exclude_columns=EXCLUDE_COLUMNS
)

@bp.route("/topic/<int:topic_id>/mark_read")
def _mark_read_for_topic(topic_id):
    need_auth()
    topic = Topic.query.get_or_404(topic_id)
    topic.mark_read(g.token_user)
    return jsonify({"code": 200})

def <REPLACE_END> <|endoftext|> # -*- coding:utf-8 -*-
from flask import g, jsonify

from gather.api import need_auth, EXCLUDE_COLUMNS

from gather.extensions import api_manager
from gather.topic.models import Topic, Reply

bp = api_manager.create_api_blueprint(
    Topic,
    methods=["GET", "POST"],
    preprocessors={
        'POST': [need_auth],
    },
    include_methods=["have_read"],
    exclude_columns=EXCLUDE_COLUMNS
)

@bp.route("/topic/<int:topic_id>/mark_read")
def _mark_read_for_topic(topic_id):
    need_auth()
    topic = Topic.query.get_or_404(topic_id)
    topic.mark_read(g.token_user)
    return jsonify({"code": 200})

def _update_topic_updated(result=None, **kw):
    if not result:
        return
    reply = Reply.query.get(result["id"])
    reply.topic.updated = reply.created
    reply.topic.clear_read()
    reply.topic.save()

reply_bp = api_manager.create_api_blueprint(
    Reply,
    methods=["POST"],
    preprocessors={
        'POST': [need_auth],
    },
    postprocessors={
        'POST': [_update_topic_updated]
    },
    exclude_columns=EXCLUDE_COLUMNS
)

Prompt:
Add API to mark topic as reader

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

from gather.api import need_auth, EXCLUDE_COLUMNS

from gather.extensions import api_manager
from gather.topic.models import Topic, Reply

bp = api_manager.create_api_blueprint(
    Topic,
    methods=["GET", "POST"],
    preprocessors={
        'POST': [need_auth],
    },
    include_methods=["have_read"],
    exclude_columns=EXCLUDE_COLUMNS
)

def _update_topic_updated(result=None, **kw):
    if not result:
        return
    reply = Reply.query.get(result["id"])
    reply.topic.updated = reply.created
    reply.topic.clear_read()
    reply.topic.save()

reply_bp = api_manager.create_api_blueprint(
    Reply,
    methods=["POST"],
    preprocessors={
        'POST': [need_auth],
    },
    postprocessors={
        'POST': [_update_topic_updated]
    },
    exclude_columns=EXCLUDE_COLUMNS
)


Response:
<INSERT>
    <INSERT_END> <INSERT> no_update=no_update)
        pull(student, <INSERT_END> <DELETE>        pull(student, no_update=no_update)
 <DELETE_END> <REPLACE_OLD> interact=interact)

 <REPLACE_NEW> interact=interact)
 <REPLACE_END> <|endoftext|> from cs251tk.student import remove
from cs251tk.student import clone_student
from cs251tk.student import stash
from cs251tk.student import pull
from cs251tk.student import checkout_date
from cs251tk.student import record
from cs251tk.student import reset
from cs251tk.student import analyze

def process_student(
    student,
    *,
    assignments,
    basedir,
    clean,
    date,
    debug,
    interact,
    no_check,
    no_update,
    specs,
    stogit_url
):
    if clean:
        remove(student)

    clone_student(student, baseurl=stogit_url)

    try:
        stash(student, no_update=no_update)
        pull(student, no_update=no_update)

        checkout_date(student, date=date)

        recordings = record(student, specs=specs, to_record=assignments, basedir=basedir, debug=debug, interact=interact)
        analysis = analyze(student, specs, check_for_branches=not no_check)

        if date:
            reset(student)

        return analysis, recordings

    except Exception as err:
        if debug:
            raise err
        return {'username': student, 'error': err}, []

Prompt:
Remove extra newlines added during editing

from cs251tk.student import remove
from cs251tk.student import clone_student
from cs251tk.student import stash
from cs251tk.student import pull
from cs251tk.student import checkout_date
from cs251tk.student import record
from cs251tk.student import reset
from cs251tk.student import analyze

def process_student(
    student,
    *,
    assignments,
    basedir,
    clean,
    date,
    debug,
    interact,
    no_check,
    no_update,
    specs,
    stogit_url
):
    if clean:
        remove(student)
    clone_student(student, baseurl=stogit_url)

    try:
        stash(student, no_update=no_update)

        pull(student, no_update=no_update)
        checkout_date(student, date=date)

        recordings = record(student, specs=specs, to_record=assignments, basedir=basedir, debug=debug, interact=interact)

        analysis = analyze(student, specs, check_for_branches=not no_check)

        if date:
            reset(student)

        return analysis, recordings

    except Exception as err:
        if debug:
            raise err
        return {'username': student, 'error': err}, []


import json
from unittest import TestCase

from usb import create_application
from usb.models import db

class APITestCase(TestCase):

    def setUp(self):
        self.app = create_application('config/test.py')
        self.client = self.app.test_client()

        db.app = self.app
        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all()

    def test_redirect_from_index_namespace(self):
        pass

    def test_redirect_from_links_namespace(self):
        pass

    def test_create_short_link(self):
        pass

    def test_update_short_link(self):
        pass

    def test_get_list_of_short_links(self):
        pass

    def test_get_list_of_short_links_empty_db(self):
        response = self.client.get('/links')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.headers['Content-Type'], 'application/json')
        data = json.loads(response.data)
        self.assertEqual(data, {})

Test content type for JSON API

Test content type for JSON API

Response:
<INSERT> self.assertEqual(response.headers['Content-Type'], 'application/json')
        <INSERT_END> <|endoftext|> import json
from unittest import TestCase

from usb import create_application
from usb.models import db

class APITestCase(TestCase):

    def setUp(self):
        self.app = create_application('config/test.py')
        self.client = self.app.test_client()

        db.app = self.app
        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all()

    def test_redirect_from_index_namespace(self):
        pass

    def test_redirect_from_links_namespace(self):
        pass

    def test_create_short_link(self):
        pass

    def test_update_short_link(self):
        pass

    def test_get_list_of_short_links(self):
        pass

    def test_get_list_of_short_links_empty_db(self):
        response = self.client.get('/links')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.headers['Content-Type'], 'application/json')
        data = json.loads(response.data)
        self.assertEqual(data, {})

Prompt:
Test content type for JSON API

import json
from unittest import TestCase

from usb import create_application
from usb.models import db

class APITestCase(TestCase):

    def setUp(self):
        self.app = create_application('config/test.py')
        self.client = self.app.test_client()

        db.app = self.app
        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all()

    def test_redirect_from_index_namespace(self):
        pass

    def test_redirect_from_links_namespace(self):
        pass

    def test_create_short_link(self):
        pass

    def test_update_short_link(self):
        pass

    def test_get_list_of_short_links(self):
        pass

    def test_get_list_of_short_links_empty_db(self):
        response = self.client.get('/links')
        self.assertEqual(response.status_code, 200)
        data = json.loads(response.data)
        self.assertEqual(data, {})


from SimpleCV import *
winsize = (640,480)
display = Display(winsize)
video = VirtualCamera('stefan_eye.mp4', 'video')
while display.isNotDone():
    image = video.getImage().rotate(90).crop(850,50,400,400)
    image2 = image.colorDistance(Color.RED)
    blobs = image2.findBlobs()
    image3 = image2.grayscale()
    if blobs:
        for b in blobs:
            if b.isCircle(0.7) and b.radius() > 3:
                image.drawCircle((b.x,b.y),b.radius(),Color.YELLOW,2)
    image.show()

Response:
<REPLACE_OLD> Display(winsize)

video <REPLACE_NEW> Display(winsize)
video <REPLACE_END> <REPLACE_OLD> a <REPLACE_NEW> image <REPLACE_END> <REPLACE_OLD> video.getImage()
 <REPLACE_NEW> video.getImage().rotate(90).crop(850,50,400,400)
 <REPLACE_END> <REPLACE_OLD> a.rotate(90).invert().toGray().binarize().save(display)

 <REPLACE_NEW> image2 = image.colorDistance(Color.RED)
    blobs = image2.findBlobs()
    image3 = image2.grayscale()
    if blobs:
        for b in blobs:
            if b.isCircle(0.7) and b.radius() > 3:
                image.drawCircle((b.x,b.y),b.radius(),Color.YELLOW,2)
    image.show()
 <REPLACE_END> <|endoftext|> from SimpleCV import *
winsize = (640,480)
display = Display(winsize)
video = VirtualCamera('stefan_eye.mp4', 'video')
while display.isNotDone():
    image = video.getImage().rotate(90).crop(850,50,400,400)
    image2 = image.colorDistance(Color.RED)
    blobs = image2.findBlobs()
    image3 = image2.grayscale()
    if blobs:
        for b in blobs:
            if b.isCircle(0.7) and b.radius() > 3:
                image.drawCircle((b.x,b.y),b.radius(),Color.YELLOW,2)
    image.show()

Prompt:
Add code to accomodate a new '3 circles' approach

from SimpleCV import *
winsize = (640,480)
display = Display(winsize)

video = VirtualCamera('stefan_eye.mp4', 'video')
while display.isNotDone():
    a = video.getImage()
    a.rotate(90).invert().toGray().binarize().save(display)