import logging
from collections import defaultdict

from indra.literature.elsevier_client import logger as elsevier_logger
from indra.literature import pubmed_client, pmc_client, elsevier_client

logger = logging.getLogger('disambiguate')

# the elsevier_client will log messages that it is safe to ignore
elsevier_logger.setLevel(logging.WARNING)

def get_fulltexts_from_entrez(hgnc_name):
    pmids = pubmed_client.get_ids_for_gene(hgnc_name)
    articles = (pubmed_client.get_article_xml(pmid) for pmid in pmids)
    fulltexts = [_universal_extract_text(article) for article in articles]
    return fulltexts

def _universal_extract_text(xml):
    # first try to parse the xml as if it came from elsevier. if we do not
    # have valid elsevier xml this will throw an exception.
    # the text extraction function in the pmc client may not throw an
    # exception when parsing elsevier xml, silently processing the xml
    # incorrectly
    try:
        fulltext = elsevier_client.extract_text(xml)
    except Exception:
        try:
            fulltext = pmc_client.extract_text(xml)
        except Exception:
            # fall back by returning input string unmodified
            fulltext = xml
    return fulltext

def _get_text_from_pmids(pmids):
    pmc_content = set(pubmed_client.filter_pmids(pmids))
    pmc_ids = (pmc_client.id_lookup(pmid, idtype='pmid')['pmcid']
               for pmid in pmc_content)
    pmc_xmls = (pmc_client.get_xml(pmc_id) for pmc_id in pmc_ids)
    pmc_texts = set(_universal_extract_text(xml) for xml in pmc_xmls)

    other_content = set(pmids) - pmc_content
    ids = (pmc_client.id_lookup(pmid, idtype='pmid') for pmid in pmids)
    elsevier_content = (elsevier_client.download_article_from_id(pmid)
                        for pmid in pmids)

Add unfinished scripts that assist in deft disambiguation

git history was completley farbed through carelessness. the original deft
branch was deleted and a new branch was created

Response:
<REPLACE_OLD>  <REPLACE_NEW> import logging
from collections import defaultdict

from indra.literature.elsevier_client import logger as elsevier_logger
from indra.literature import pubmed_client, pmc_client, elsevier_client

logger = logging.getLogger('disambiguate')

# the elsevier_client will log messages that it is safe to ignore
elsevier_logger.setLevel(logging.WARNING)

def get_fulltexts_from_entrez(hgnc_name):
    pmids = pubmed_client.get_ids_for_gene(hgnc_name)
    articles = (pubmed_client.get_article_xml(pmid) for pmid in pmids)
    fulltexts = [_universal_extract_text(article) for article in articles]
    return fulltexts

def _universal_extract_text(xml):
    # first try to parse the xml as if it came from elsevier. if we do not
    # have valid elsevier xml this will throw an exception.
    # the text extraction function in the pmc client may not throw an
    # exception when parsing elsevier xml, silently processing the xml
    # incorrectly
    try:
        fulltext = elsevier_client.extract_text(xml)
    except Exception:
        try:
            fulltext = pmc_client.extract_text(xml)
        except Exception:
            # fall back by returning input string unmodified
            fulltext = xml
    return fulltext

def _get_text_from_pmids(pmids):
    pmc_content = set(pubmed_client.filter_pmids(pmids))
    pmc_ids = (pmc_client.id_lookup(pmid, idtype='pmid')['pmcid']
               for pmid in pmc_content)
    pmc_xmls = (pmc_client.get_xml(pmc_id) for pmc_id in pmc_ids)
    pmc_texts = set(_universal_extract_text(xml) for xml in pmc_xmls)

    other_content = set(pmids) - pmc_content
    ids = (pmc_client.id_lookup(pmid, idtype='pmid') for pmid in pmids)
    elsevier_content = (elsevier_client.download_article_from_id(pmid)
                        for pmid in pmids)

 <REPLACE_END> <|endoftext|> import logging
from collections import defaultdict

from indra.literature.elsevier_client import logger as elsevier_logger
from indra.literature import pubmed_client, pmc_client, elsevier_client

logger = logging.getLogger('disambiguate')

# the elsevier_client will log messages that it is safe to ignore
elsevier_logger.setLevel(logging.WARNING)

def get_fulltexts_from_entrez(hgnc_name):
    pmids = pubmed_client.get_ids_for_gene(hgnc_name)
    articles = (pubmed_client.get_article_xml(pmid) for pmid in pmids)
    fulltexts = [_universal_extract_text(article) for article in articles]
    return fulltexts

def _universal_extract_text(xml):
    # first try to parse the xml as if it came from elsevier. if we do not
    # have valid elsevier xml this will throw an exception.
    # the text extraction function in the pmc client may not throw an
    # exception when parsing elsevier xml, silently processing the xml
    # incorrectly
    try:
        fulltext = elsevier_client.extract_text(xml)
    except Exception:
        try:
            fulltext = pmc_client.extract_text(xml)
        except Exception:
            # fall back by returning input string unmodified
            fulltext = xml
    return fulltext

def _get_text_from_pmids(pmids):
    pmc_content = set(pubmed_client.filter_pmids(pmids))
    pmc_ids = (pmc_client.id_lookup(pmid, idtype='pmid')['pmcid']
               for pmid in pmc_content)
    pmc_xmls = (pmc_client.get_xml(pmc_id) for pmc_id in pmc_ids)
    pmc_texts = set(_universal_extract_text(xml) for xml in pmc_xmls)

    other_content = set(pmids) - pmc_content
    ids = (pmc_client.id_lookup(pmid, idtype='pmid') for pmid in pmids)
    elsevier_content = (elsevier_client.download_article_from_id(pmid)
                        for pmid in pmids)

Prompt:
Add unfinished scripts that assist in deft disambiguation

git history was completley farbed through carelessness. the original deft
branch was deleted and a new branch was created


from __future__ import unicode_literals

from django.conf import settings
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext as _

@python_2_unicode_compatible
class Tag(models.Model):
    slug = models.SlugField(unique=True)
    description = models.TextField(null=True, blank=True)

    def __str__(self):
        return self.slug

@python_2_unicode_compatible
class Wallet(models.Model):
    CURRENCIES = (
        ("EUR", "EUR"),
    )
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='wallets')
    label = models.CharField(max_length=100)
    description = models.TextField(null=True, blank=True)
    currency = models.CharField(max_length=3, null=False, blank=False, choices=CURRENCIES)

    def __str__(self):
        return "{} ({})".format(self.label, self.currency)

@python_2_unicode_compatible
class Movement(models.Model):
    wallet = models.ForeignKey(Wallet, related_name="movements")
    date = models.DateTimeField(default=timezone.now())
    amount = models.DecimalField(max_digits=11, decimal_places=2)

    tags = models.ManyToManyField(Tag, related_name="movements")

    def __str__(self):
        return "{} - {:.2f} for {} on {}".format(
            self.type, self.amount, self.wallet, self.date)

Add default to movement date

Add default to movement date

Response:
<INSERT> django.utils import timezone
from <INSERT_END> <REPLACE_OLD> models.DateTimeField()
 <REPLACE_NEW> models.DateTimeField(default=timezone.now())
 <REPLACE_END> <|endoftext|> from __future__ import unicode_literals

from django.conf import settings
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext as _

@python_2_unicode_compatible
class Tag(models.Model):
    slug = models.SlugField(unique=True)
    description = models.TextField(null=True, blank=True)

    def __str__(self):
        return self.slug

@python_2_unicode_compatible
class Wallet(models.Model):
    CURRENCIES = (
        ("EUR", "EUR"),
    )
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='wallets')
    label = models.CharField(max_length=100)
    description = models.TextField(null=True, blank=True)
    currency = models.CharField(max_length=3, null=False, blank=False, choices=CURRENCIES)

    def __str__(self):
        return "{} ({})".format(self.label, self.currency)

@python_2_unicode_compatible
class Movement(models.Model):
    wallet = models.ForeignKey(Wallet, related_name="movements")
    date = models.DateTimeField(default=timezone.now())
    amount = models.DecimalField(max_digits=11, decimal_places=2)

    tags = models.ManyToManyField(Tag, related_name="movements")

    def __str__(self):
        return "{} - {:.2f} for {} on {}".format(
            self.type, self.amount, self.wallet, self.date)

Prompt:
Add default to movement date

from __future__ import unicode_literals

from django.conf import settings
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext as _

@python_2_unicode_compatible
class Tag(models.Model):
    slug = models.SlugField(unique=True)
    description = models.TextField(null=True, blank=True)

    def __str__(self):
        return self.slug

@python_2_unicode_compatible
class Wallet(models.Model):
    CURRENCIES = (
        ("EUR", "EUR"),
    )
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='wallets')
    label = models.CharField(max_length=100)
    description = models.TextField(null=True, blank=True)
    currency = models.CharField(max_length=3, null=False, blank=False, choices=CURRENCIES)

    def __str__(self):
        return "{} ({})".format(self.label, self.currency)

@python_2_unicode_compatible
class Movement(models.Model):
    wallet = models.ForeignKey(Wallet, related_name="movements")
    date = models.DateTimeField()
    amount = models.DecimalField(max_digits=11, decimal_places=2)

    tags = models.ManyToManyField(Tag, related_name="movements")

    def __str__(self):
        return "{} - {:.2f} for {} on {}".format(
            self.type, self.amount, self.wallet, self.date)


from __future__ import absolute_import, division, print_function, unicode_literals

import os
import base64
import credsmash.aes_ctr
import credsmash.aes_gcm

class DummyKeyService(object):
    def generate_key_data(self, number_of_bytes):
        key = os.urandom(int(number_of_bytes))
        return key, base64.b64encode(key)

    def decrypt(self, encoded_key):
        return base64.b64decode(encoded_key)

def test_aes_ctr_legacy():
    """
    Basic test to ensure `cryptography` is installed/working
    """
    key_service = DummyKeyService()

    plaintext = b'abcdefghi'
    material = credsmash.aes_ctr.seal_aes_ctr_legacy(
        key_service,
        plaintext
    )
    recovered_plaintext = credsmash.aes_ctr.open_aes_ctr_legacy(
        key_service, material
    )
    assert plaintext == recovered_plaintext

def test_aes_ctr():
    key_service = DummyKeyService()

    plaintext = b'abcdefghi'
    material = credsmash.aes_ctr.seal_aes_ctr(
        key_service,
        plaintext
    )
    recovered_plaintext = credsmash.aes_ctr.open_aes_ctr(
        key_service, material
    )
    assert plaintext == recovered_plaintext

def test_aes_gcm():
    key_service = DummyKeyService()

    plaintext = b'abcdefghi'
    material = credsmash.aes_gcm.seal_aes_gcm(
        key_service,
        plaintext
    )
    recovered_plaintext = credsmash.aes_gcm.open_aes_gcm(
        key_service, material
    )
    assert plaintext == recovered_plaintext

Add test to show crypto working

Add test to show crypto working

Response:
<REPLACE_OLD>  <REPLACE_NEW> from __future__ import absolute_import, division, print_function, unicode_literals

import os
import base64
import credsmash.aes_ctr
import credsmash.aes_gcm

class DummyKeyService(object):
    def generate_key_data(self, number_of_bytes):
        key = os.urandom(int(number_of_bytes))
        return key, base64.b64encode(key)

    def decrypt(self, encoded_key):
        return base64.b64decode(encoded_key)

def test_aes_ctr_legacy():
    """
    Basic test to ensure `cryptography` is installed/working
    """
    key_service = DummyKeyService()

    plaintext = b'abcdefghi'
    material = credsmash.aes_ctr.seal_aes_ctr_legacy(
        key_service,
        plaintext
    )
    recovered_plaintext = credsmash.aes_ctr.open_aes_ctr_legacy(
        key_service, material
    )
    assert plaintext == recovered_plaintext

def test_aes_ctr():
    key_service = DummyKeyService()

    plaintext = b'abcdefghi'
    material = credsmash.aes_ctr.seal_aes_ctr(
        key_service,
        plaintext
    )
    recovered_plaintext = credsmash.aes_ctr.open_aes_ctr(
        key_service, material
    )
    assert plaintext == recovered_plaintext

def test_aes_gcm():
    key_service = DummyKeyService()

    plaintext = b'abcdefghi'
    material = credsmash.aes_gcm.seal_aes_gcm(
        key_service,
        plaintext
    )
    recovered_plaintext = credsmash.aes_gcm.open_aes_gcm(
        key_service, material
    )
    assert plaintext == recovered_plaintext

 <REPLACE_END> <|endoftext|> from __future__ import absolute_import, division, print_function, unicode_literals

import os
import base64
import credsmash.aes_ctr
import credsmash.aes_gcm

class DummyKeyService(object):
    def generate_key_data(self, number_of_bytes):
        key = os.urandom(int(number_of_bytes))
        return key, base64.b64encode(key)

    def decrypt(self, encoded_key):
        return base64.b64decode(encoded_key)

def test_aes_ctr_legacy():
    """
    Basic test to ensure `cryptography` is installed/working
    """
    key_service = DummyKeyService()

    plaintext = b'abcdefghi'
    material = credsmash.aes_ctr.seal_aes_ctr_legacy(
        key_service,
        plaintext
    )
    recovered_plaintext = credsmash.aes_ctr.open_aes_ctr_legacy(
        key_service, material
    )
    assert plaintext == recovered_plaintext

def test_aes_ctr():
    key_service = DummyKeyService()

    plaintext = b'abcdefghi'
    material = credsmash.aes_ctr.seal_aes_ctr(
        key_service,
        plaintext
    )
    recovered_plaintext = credsmash.aes_ctr.open_aes_ctr(
        key_service, material
    )
    assert plaintext == recovered_plaintext

def test_aes_gcm():
    key_service = DummyKeyService()

    plaintext = b'abcdefghi'
    material = credsmash.aes_gcm.seal_aes_gcm(
        key_service,
        plaintext
    )
    recovered_plaintext = credsmash.aes_gcm.open_aes_gcm(
        key_service, material
    )
    assert plaintext == recovered_plaintext

Prompt: Add test to show crypto working


import logging
from flexget.plugin import register_plugin

log = logging.getLogger('listdir')

class InputListdir:
    """
        Uses local path content as an input.

        Example:

        listdir: /storage/movies/
    """

    def validator(self):
        from flexget import validator
        root = validator.factory()
        root.accept('path')
        bundle = root.accept('list')
        bundle.accept('path')
        return root

    def get_config(self, feed):
        config = feed.config.get('listdir', None)
        # If only a single path is passed turn it into a 1 element list
        if isinstance(config, basestring):
            config = [config]
        return config

    def on_feed_input(self, feed):
        from flexget.feed import Entry
        import os
        config = self.get_config(feed)
        for path in config:
            for name in os.listdir(unicode(path)):
                e = Entry()
                e['title'] = name
                filepath = os.path.join(path, name)
                # Windows paths need an extra / prepended to them
                if not filepath.startswith('/'):
                    filepath = '/' + filepath
                e['url'] = 'file://%s' % (filepath)
                e['location'] = os.path.join(path, name)
                feed.entries.append(e)

register_plugin(InputListdir, 'listdir')

Response:
<REPLACE_OLD> *

log <REPLACE_NEW> register_plugin

log <REPLACE_END> <REPLACE_OLD> input.

        Example:

 <REPLACE_NEW> input.

        Example:

 <REPLACE_END> <REPLACE_OLD> """

 <REPLACE_NEW> """

 <REPLACE_END> <REPLACE_OLD> root

 <REPLACE_NEW> root

 <REPLACE_END> <REPLACE_OLD> #if <REPLACE_NEW> # If <REPLACE_END> <REPLACE_OLD> config:
 <REPLACE_NEW> config:
 <REPLACE_END> <INSERT> filepath = os.path.join(path, name)
                # Windows paths need an extra / prepended to them
                if not filepath.startswith('/'):
                    filepath = '/' + filepath
                <INSERT_END> <REPLACE_OLD> (os.path.join(path, name))
 <REPLACE_NEW> (filepath)
 <REPLACE_END> <|endoftext|> import logging
from flexget.plugin import register_plugin

log = logging.getLogger('listdir')

class InputListdir:
    """
        Uses local path content as an input.

        Example:

        listdir: /storage/movies/
    """

    def validator(self):
        from flexget import validator
        root = validator.factory()
        root.accept('path')
        bundle = root.accept('list')
        bundle.accept('path')
        return root

    def get_config(self, feed):
        config = feed.config.get('listdir', None)
        # If only a single path is passed turn it into a 1 element list
        if isinstance(config, basestring):
            config = [config]
        return config

    def on_feed_input(self, feed):
        from flexget.feed import Entry
        import os
        config = self.get_config(feed)
        for path in config:
            for name in os.listdir(unicode(path)):
                e = Entry()
                e['title'] = name
                filepath = os.path.join(path, name)
                # Windows paths need an extra / prepended to them
                if not filepath.startswith('/'):
                    filepath = '/' + filepath
                e['url'] = 'file://%s' % (filepath)
                e['location'] = os.path.join(path, name)
                feed.entries.append(e)

register_plugin(InputListdir, 'listdir')

Prompt:
Fix url of entries made by listdir on Windows.

git-svn-id: ad91b9aa7ba7638d69f912c9f5d012e3326e9f74@1586 3942dd89-8c5d-46d7-aeed-044bccf3e60c

import logging
from flexget.plugin import *

log = logging.getLogger('listdir')

class InputListdir:
    """
        Uses local path content as an input.

        Example:

        listdir: /storage/movies/
    """

    def validator(self):
        from flexget import validator
        root = validator.factory()
        root.accept('path')
        bundle = root.accept('list')
        bundle.accept('path')
        return root

    def get_config(self, feed):
        config = feed.config.get('listdir', None)
        #if only a single path is passed turn it into a 1 element list
        if isinstance(config, basestring):
            config = [config]
        return config

    def on_feed_input(self, feed):
        from flexget.feed import Entry
        import os
        config = self.get_config(feed)
        for path in config:
            for name in os.listdir(unicode(path)):
                e = Entry()
                e['title'] = name
                e['url'] = 'file://%s' % (os.path.join(path, name))
                e['location'] = os.path.join(path, name)
                feed.entries.append(e)

register_plugin(InputListdir, 'listdir')


from setuptools import setup
from setuptools.command.install import install as _install

class install(_install):
    def run(self):
        _install.run(self)

setup(
    cmdclass = { 'install' : install },
    name = 'hydra',
    version = '0.1',
    author = 'tatsy',
    author_email = 'tatsy.mail@gmail.com',
    url = 'https://github.com/tatsy/hydra.git',
    description = 'Python HDR image processing library.',
    license = 'MIT',
    classifiers = [
        'Development Status :: 1 - Planning',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4'
    ],
    packages = [
        'hydra',
        'hydra.core',
        'hydra.eo',
        'hydra.filters',
        'hydra.gen',
        'hydra.io',
        'hydra.tonemap'
    ]
)

Add eo to installed packages.

Add eo to installed packages.

Response:
<INSERT> 'hydra.eo',
        'hydra.filters',
        <INSERT_END> <DELETE> 'hydra.filters',
        <DELETE_END> <|endoftext|> from setuptools import setup
from setuptools.command.install import install as _install

class install(_install):
    def run(self):
        _install.run(self)

setup(
    cmdclass = { 'install' : install },
    name = 'hydra',
    version = '0.1',
    author = 'tatsy',
    author_email = 'tatsy.mail@gmail.com',
    url = 'https://github.com/tatsy/hydra.git',
    description = 'Python HDR image processing library.',
    license = 'MIT',
    classifiers = [
        'Development Status :: 1 - Planning',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4'
    ],
    packages = [
        'hydra',
        'hydra.core',
        'hydra.eo',
        'hydra.filters',
        'hydra.gen',
        'hydra.io',
        'hydra.tonemap'
    ]
)

Prompt:
Add eo to installed packages.

from setuptools import setup
from setuptools.command.install import install as _install

class install(_install):
    def run(self):
        _install.run(self)

setup(
    cmdclass = { 'install' : install },
    name = 'hydra',
    version = '0.1',
    author = 'tatsy',
    author_email = 'tatsy.mail@gmail.com',
    url = 'https://github.com/tatsy/hydra.git',
    description = 'Python HDR image processing library.',
    license = 'MIT',
    classifiers = [
        'Development Status :: 1 - Planning',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4'
    ],
    packages = [
        'hydra',
        'hydra.core',
        'hydra.gen',
        'hydra.io',
        'hydra.filters',
        'hydra.tonemap'
    ]
)


"""Django haystack `SearchIndex` module."""
from pages.models import Page, Content

from haystack.indexes import SearchIndex, CharField, DateTimeField
from haystack import site

import datetime

class PageIndex(SearchIndex):
    """Search index for pages content."""
    text = CharField(document=True, use_template=True)
    title = CharField(model_attr='title')
    url = CharField(model_attr='get_absolute_url')
    publication_date = DateTimeField(model_attr='publication_date')

    def get_queryset(self):
        """Used when the entire index for model is updated."""
        return Page.objects.published()

site.register(Page, PageIndex)

Response:
<INSERT> url = CharField(model_attr='get_absolute_url')
    <INSERT_END> <|endoftext|> """Django haystack `SearchIndex` module."""
from pages.models import Page, Content

from haystack.indexes import SearchIndex, CharField, DateTimeField
from haystack import site

import datetime

class PageIndex(SearchIndex):
    """Search index for pages content."""
    text = CharField(document=True, use_template=True)
    title = CharField(model_attr='title')
    url = CharField(model_attr='get_absolute_url')
    publication_date = DateTimeField(model_attr='publication_date')

    def get_queryset(self):
        """Used when the entire index for model is updated."""
        return Page.objects.published()

site.register(Page, PageIndex)

Prompt:
Add a url attribute to the SearchIndex for pages.

This is useful when displaying a list of search results because we
can create a link to the result without having to hit the database
for every object in the result list.

"""Django haystack `SearchIndex` module."""
from pages.models import Page, Content

from haystack.indexes import SearchIndex, CharField, DateTimeField
from haystack import site

import datetime

class PageIndex(SearchIndex):
    """Search index for pages content."""
    text = CharField(document=True, use_template=True)
    title = CharField(model_attr='title')
    publication_date = DateTimeField(model_attr='publication_date')

    def get_queryset(self):
        """Used when the entire index for model is updated."""
        return Page.objects.published()

site.register(Page, PageIndex)


from django.core.management.base import BaseCommand, CommandError
from ...models import Render

class Command(BaseCommand):
    help = 'Deletes output of all expired renders'

    def handle(self, *args, **options):
        for render in Render.objects.expired().iterator():
            try:
                render.delete_output()
            except FileNotFoundError:
                print(f"❌  Render {render.id} already deleted", flush=True)
            else:
                print(f"✅  Render {render.id} deleted", flush=True)

Add flush to delete all renders print

Add flush to delete all renders print

Response:
<REPLACE_OLD> deleted")
 <REPLACE_NEW> deleted", flush=True)
 <REPLACE_END> <REPLACE_OLD> deleted")

 <REPLACE_NEW> deleted", flush=True)

 <REPLACE_END> <|endoftext|> from django.core.management.base import BaseCommand, CommandError
from ...models import Render

class Command(BaseCommand):
    help = 'Deletes output of all expired renders'

    def handle(self, *args, **options):
        for render in Render.objects.expired().iterator():
            try:
                render.delete_output()
            except FileNotFoundError:
                print(f"❌  Render {render.id} already deleted", flush=True)
            else:
                print(f"✅  Render {render.id} deleted", flush=True)

Prompt:
Add flush to delete all renders print

from django.core.management.base import BaseCommand, CommandError
from ...models import Render

class Command(BaseCommand):
    help = 'Deletes output of all expired renders'

    def handle(self, *args, **options):
        for render in Render.objects.expired().iterator():
            try:
                render.delete_output()
            except FileNotFoundError:
                print(f"❌  Render {render.id} already deleted")
            else:
                print(f"✅  Render {render.id} deleted")


# -*- coding: utf-8 -*-
# Copyright <YEAR(S)> <AUTHOR(S)>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

from openerp.tests.common import HttpCase, TransactionCase

class SomethingCase(TransactionCase):
    def setUp(self, *args, **kwargs):
        super(SomethingCase, self).setUp(*args, **kwargs)

        # TODO Replace this for something useful or delete this method
        self.do_something_before_all_tests()

    def tearDown(self, *args, **kwargs):
        # TODO Replace this for something useful or delete this method
        self.do_something_after_all_tests()

        return super(SomethingCase, self).tearDown(*args, **kwargs)

    def test_something(self):
        """First line of docstring appears in test logs.

        Other lines do not.

        Any method starting with ``test_`` will be tested.
        """
        pass

class UICase(HttpCase):
    def test_ui_web(self):
        """Test backend tests."""
        self.phantom_js("/web/tests?debug=assets&module=module_name", "", login="admin")

    def test_ui_website(self):
        """Test frontend tour."""
        self.phantom_js(
            url_path="/?debug=assets",
            code="odoo.__DEBUG__.services['web.Tour']"
                 ".run('test_module_name', 'test')",
            ready="odoo.__DEBUG__.services['web.Tour'].tours.test_module_name",
            login="admin")

Add debug assets to HTTP cases

[IMP] Add debug assets to HTTP cases

Response:
<REPLACE_OLD> self.phantom_js("/web/tests?module=module_name", <REPLACE_NEW> self.phantom_js("/web/tests?debug=assets&module=module_name", <REPLACE_END> <REPLACE_OLD> url_path="/",
 <REPLACE_NEW> url_path="/?debug=assets",
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
# Copyright <YEAR(S)> <AUTHOR(S)>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

from openerp.tests.common import HttpCase, TransactionCase

class SomethingCase(TransactionCase):
    def setUp(self, *args, **kwargs):
        super(SomethingCase, self).setUp(*args, **kwargs)

        # TODO Replace this for something useful or delete this method
        self.do_something_before_all_tests()

    def tearDown(self, *args, **kwargs):
        # TODO Replace this for something useful or delete this method
        self.do_something_after_all_tests()

        return super(SomethingCase, self).tearDown(*args, **kwargs)

    def test_something(self):
        """First line of docstring appears in test logs.

        Other lines do not.

        Any method starting with ``test_`` will be tested.
        """
        pass

class UICase(HttpCase):
    def test_ui_web(self):
        """Test backend tests."""
        self.phantom_js("/web/tests?debug=assets&module=module_name", "", login="admin")

    def test_ui_website(self):
        """Test frontend tour."""
        self.phantom_js(
            url_path="/?debug=assets",
            code="odoo.__DEBUG__.services['web.Tour']"
                 ".run('test_module_name', 'test')",
            ready="odoo.__DEBUG__.services['web.Tour'].tours.test_module_name",
            login="admin")

Prompt:
[IMP] Add debug assets to HTTP cases

# -*- coding: utf-8 -*-
# Copyright <YEAR(S)> <AUTHOR(S)>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

from openerp.tests.common import HttpCase, TransactionCase

class SomethingCase(TransactionCase):
    def setUp(self, *args, **kwargs):
        super(SomethingCase, self).setUp(*args, **kwargs)

        # TODO Replace this for something useful or delete this method
        self.do_something_before_all_tests()

    def tearDown(self, *args, **kwargs):
        # TODO Replace this for something useful or delete this method
        self.do_something_after_all_tests()

        return super(SomethingCase, self).tearDown(*args, **kwargs)

    def test_something(self):
        """First line of docstring appears in test logs.

        Other lines do not.

        Any method starting with ``test_`` will be tested.
        """
        pass

class UICase(HttpCase):
    def test_ui_web(self):
        """Test backend tests."""
        self.phantom_js("/web/tests?module=module_name", "", login="admin")

    def test_ui_website(self):
        """Test frontend tour."""
        self.phantom_js(
            url_path="/",
            code="odoo.__DEBUG__.services['web.Tour']"
                 ".run('test_module_name', 'test')",
            ready="odoo.__DEBUG__.services['web.Tour'].tours.test_module_name",
            login="admin")


import pytest
from web_test_base import *

class TestIATIRegistry(WebTestBase):
    urls_to_get = [
        "http://iatiregistry.org/"
        , "http://www.iatiregistry.org/"
        , "https://iatiregistry.org/"
        , "https://www.iatiregistry.org/"
    ]

    def test_contains_links(self, loaded_request):
        """
        Test that each page contains links to the defined URLs.
        """
        result = self._get_links_from_page(loaded_request)

        assert "http://www.aidtransparency.net/" in result
        assert "http://www.iatistandard.org/" in result

Add tests for the IATI Registry This adds a 200 response and link checks for the IATI Registry

Response:
<INSERT> import pytest
from web_test_base import *

class TestIATIRegistry(WebTestBase):
 <INSERT_END> <INSERT>   urls_to_get = [
        "http://iatiregistry.org/"
        , "http://www.iatiregistry.org/"
        , "https://iatiregistry.org/"
        , "https://www.iatiregistry.org/"
    ]

    def test_contains_links(self, loaded_request):
        """
        Test that each page contains links to the defined URLs.
        """
        result = self._get_links_from_page(loaded_request)

        assert "http://www.aidtransparency.net/" in result
        assert "http://www.iatistandard.org/" in result
 <INSERT_END> <|endoftext|> import pytest
from web_test_base import *

class TestIATIRegistry(WebTestBase):
    urls_to_get = [
        "http://iatiregistry.org/"
        , "http://www.iatiregistry.org/"
        , "https://iatiregistry.org/"
        , "https://www.iatiregistry.org/"
    ]

    def test_contains_links(self, loaded_request):
        """
        Test that each page contains links to the defined URLs.
        """
        result = self._get_links_from_page(loaded_request)

        assert "http://www.aidtransparency.net/" in result
        assert "http://www.iatistandard.org/" in result

Prompt:
Add tests for the IATI Registry
This adds a 200 response and link checks for the IATI Registry


import re
from os import path
import yaml

with open(path.join(path.dirname(__file__), 'capabilities.yml')) as f:
    PROFILES = yaml.load(f)

class Profile(object):

    profile_data = {}

    def __init__(self, columns=None):
        self.default_columns = columns

    def __getattr__(self, name):
        return self.profile_data[name]

    def get_columns(self, font):
        """ Return the number of columns for the given font.
        """
        if self.default_columns:
            return self.default_columns

        if 'columnConfigs' in self.profile_data:
            columns_def = self.columnConfigs[self.defaultColumnConfig]

        elif 'columns' in self.profile_data:
            columns_def = self.columns

        if isinstance(columns_def, int):
            return columns_def
        return columns_def[font]

def get_profile(name=None, **kwargs):
    if isinstance(name, Profile):
        return name

    clazz = get_profile_class(name or 'default')
    return clazz(**kwargs)

CLASS_CACHE = {}

def get_profile_class(name):
    if not name in CLASS_CACHE:
        profile_data = resolve_profile_data(name)
        class_name = '%sProfile' % clean(name)
        new_class = type(class_name, (Profile,), {'profile_data': profile_data})
        CLASS_CACHE[name] = new_class

    return CLASS_CACHE[name]

def clean(s):
   # Remove invalid characters
   s = re.sub('[^0-9a-zA-Z_]', '', s)
   # Remove leading characters until we find a letter or underscore
   s = re.sub('^[^a-zA-Z_]+', '', s)
   return str(s)

def resolve_profile_data(name):
    data = PROFILES[name]
    inherits = data.get('inherits')
    if not inherits:
        return data

    if not isinstance(inherits, (tuple, list)):
        inherits = [inherits]

    merged = {}
    for base in reversed(inherits):
        base_data = resolve_profile_data(base)
        merged.update(base_data)
    merged.update(data)
    return merged

Support loading capabilites YAML into Python classes.

Response:
<REPLACE_OLD>  <REPLACE_NEW> import re
from os import path
import yaml

with open(path.join(path.dirname(__file__), 'capabilities.yml')) as f:
    PROFILES = yaml.load(f)

class Profile(object):

    profile_data = {}

    def __init__(self, columns=None):
        self.default_columns = columns

    def __getattr__(self, name):
        return self.profile_data[name]

    def get_columns(self, font):
        """ Return the number of columns for the given font.
        """
        if self.default_columns:
            return self.default_columns

        if 'columnConfigs' in self.profile_data:
            columns_def = self.columnConfigs[self.defaultColumnConfig]

        elif 'columns' in self.profile_data:
            columns_def = self.columns

        if isinstance(columns_def, int):
            return columns_def
        return columns_def[font]

def get_profile(name=None, **kwargs):
    if isinstance(name, Profile):
        return name

    clazz = get_profile_class(name or 'default')
    return clazz(**kwargs)

CLASS_CACHE = {}

def get_profile_class(name):
    if not name in CLASS_CACHE:
        profile_data = resolve_profile_data(name)
        class_name = '%sProfile' % clean(name)
        new_class = type(class_name, (Profile,), {'profile_data': profile_data})
        CLASS_CACHE[name] = new_class

    return CLASS_CACHE[name]

def clean(s):
   # Remove invalid characters
   s = re.sub('[^0-9a-zA-Z_]', '', s)
   # Remove leading characters until we find a letter or underscore
   s = re.sub('^[^a-zA-Z_]+', '', s)
   return str(s)

def resolve_profile_data(name):
    data = PROFILES[name]
    inherits = data.get('inherits')
    if not inherits:
        return data

    if not isinstance(inherits, (tuple, list)):
        inherits = [inherits]

    merged = {}
    for base in reversed(inherits):
        base_data = resolve_profile_data(base)
        merged.update(base_data)
    merged.update(data)
    return merged

 <REPLACE_END> <|endoftext|> import re
from os import path
import yaml

with open(path.join(path.dirname(__file__), 'capabilities.yml')) as f:
    PROFILES = yaml.load(f)

class Profile(object):

    profile_data = {}

    def __init__(self, columns=None):
        self.default_columns = columns

    def __getattr__(self, name):
        return self.profile_data[name]

    def get_columns(self, font):
        """ Return the number of columns for the given font.
        """
        if self.default_columns:
            return self.default_columns

        if 'columnConfigs' in self.profile_data:
            columns_def = self.columnConfigs[self.defaultColumnConfig]

        elif 'columns' in self.profile_data:
            columns_def = self.columns

        if isinstance(columns_def, int):
            return columns_def
        return columns_def[font]

def get_profile(name=None, **kwargs):
    if isinstance(name, Profile):
        return name

    clazz = get_profile_class(name or 'default')
    return clazz(**kwargs)

CLASS_CACHE = {}

def get_profile_class(name):
    if not name in CLASS_CACHE:
        profile_data = resolve_profile_data(name)
        class_name = '%sProfile' % clean(name)
        new_class = type(class_name, (Profile,), {'profile_data': profile_data})
        CLASS_CACHE[name] = new_class

    return CLASS_CACHE[name]

def clean(s):
   # Remove invalid characters
   s = re.sub('[^0-9a-zA-Z_]', '', s)
   # Remove leading characters until we find a letter or underscore
   s = re.sub('^[^a-zA-Z_]+', '', s)
   return str(s)

def resolve_profile_data(name):
    data = PROFILES[name]
    inherits = data.get('inherits')
    if not inherits:
        return data

    if not isinstance(inherits, (tuple, list)):
        inherits = [inherits]

    merged = {}
    for base in reversed(inherits):
        base_data = resolve_profile_data(base)
        merged.update(base_data)
    merged.update(data)
    return merged

Prompt: Support loading capabilites YAML into Python classes.


from setuptools import setup, find_packages

from dimod import __version__, __author__, __description__, __authoremail__, _PY2

install_requires = ['decorator>=4.1.0']
if _PY2:
    # enum is built-in for python 3
    install_requires.append('enum')

extras_require = {'all': ['numpy']}

packages = ['dimod',
            'dimod.responses',
            'dimod.composites',
            'dimod.samplers']

setup(
    name='dimod',
    version=__version__,
    author=__author__,
    author_email=__authoremail__,
    description=__description__,
    url='https://github.com/dwavesystems/dimod',
    download_url='https://github.com/dwavesys/dimod/archive/0.1.1.tar.gz',
    license='Apache 2.0',
    packages=packages,
    install_requires=install_requires,
    extras_require=extras_require,
)

Add enum for python2 install

Add enum for python2 install

Response:
<REPLACE_OLD> __authoremail__

install_requires <REPLACE_NEW> __authoremail__, _PY2

install_requires <REPLACE_END> <REPLACE_OLD> ['decorator>=4.1.0']
extras_require <REPLACE_NEW> ['decorator>=4.1.0']
if _PY2:
    # enum is built-in for python 3
    install_requires.append('enum')

extras_require <REPLACE_END> <|endoftext|> from setuptools import setup, find_packages

from dimod import __version__, __author__, __description__, __authoremail__, _PY2

install_requires = ['decorator>=4.1.0']
if _PY2:
    # enum is built-in for python 3
    install_requires.append('enum')

extras_require = {'all': ['numpy']}

packages = ['dimod',
            'dimod.responses',
            'dimod.composites',
            'dimod.samplers']

setup(
    name='dimod',
    version=__version__,
    author=__author__,
    author_email=__authoremail__,
    description=__description__,
    url='https://github.com/dwavesystems/dimod',
    download_url='https://github.com/dwavesys/dimod/archive/0.1.1.tar.gz',
    license='Apache 2.0',
    packages=packages,
    install_requires=install_requires,
    extras_require=extras_require,
)

Prompt:
Add enum for python2 install

from setuptools import setup, find_packages

from dimod import __version__, __author__, __description__, __authoremail__

install_requires = ['decorator>=4.1.0']
extras_require = {'all': ['numpy']}

packages = ['dimod',
            'dimod.responses',
            'dimod.composites',
            'dimod.samplers']

setup(
    name='dimod',
    version=__version__,
    author=__author__,
    author_email=__authoremail__,
    description=__description__,
    url='https://github.com/dwavesystems/dimod',
    download_url='https://github.com/dwavesys/dimod/archive/0.1.1.tar.gz',
    license='Apache 2.0',
    packages=packages,
    install_requires=install_requires,
    extras_require=extras_require,
)


import os
import logging
import envoy
from .ants_error import ANTSError

def create_template(metric, files):
    """
    Builds a template from the given image files.

    :param metric: the similarity metric
    :param files: the image files
    :return: the template file name
    """
    CMD = "buildtemplateparallel.sh -d 2 -c 2 -j 4 -d 2 -s {metric} -o {output} {files}"
    PREFIX = 'reg_'
    SUFFIX = 'template.nii.gz'

    tmpl = PREFIX + SUFFIX
    if os.path.exists(tmpl):
        logging.info("Registration template already exists: %s" % tmpl)
        return tmpl
    cmd = CMD.format(metric=metric.name, output=PREFIX, files=' '.join(files))
    logging.info("Building the %s registration template with the following command:" % tmpl)
    logging.info(cmd[:80])
    r = envoy.run(cmd)
    if r.status_code:
        logging.error("Build registration template failed with error code %d" % r.status_code)
        logging.error(r.std_err)
        raise ANTSError("Build registration template unsuccessful; see the log for details")
    if not os.path.exists(tmpl):
        logging.error("Build registration template was not created.")
        raise ANTSError("Build registration template unsuccessful; see the log for details")

    logging.info("Built the registration template %s." % tmpl)
    return tmpl

Truncate a long log message.

Truncate a long log message.

Response:
<REPLACE_OLD> logging.info(cmd)
 <REPLACE_NEW> logging.info(cmd[:80])
 <REPLACE_END> <|endoftext|> import os
import logging
import envoy
from .ants_error import ANTSError

def create_template(metric, files):
    """
    Builds a template from the given image files.

    :param metric: the similarity metric
    :param files: the image files
    :return: the template file name
    """
    CMD = "buildtemplateparallel.sh -d 2 -c 2 -j 4 -d 2 -s {metric} -o {output} {files}"
    PREFIX = 'reg_'
    SUFFIX = 'template.nii.gz'

    tmpl = PREFIX + SUFFIX
    if os.path.exists(tmpl):
        logging.info("Registration template already exists: %s" % tmpl)
        return tmpl
    cmd = CMD.format(metric=metric.name, output=PREFIX, files=' '.join(files))
    logging.info("Building the %s registration template with the following command:" % tmpl)
    logging.info(cmd[:80])
    r = envoy.run(cmd)
    if r.status_code:
        logging.error("Build registration template failed with error code %d" % r.status_code)
        logging.error(r.std_err)
        raise ANTSError("Build registration template unsuccessful; see the log for details")
    if not os.path.exists(tmpl):
        logging.error("Build registration template was not created.")
        raise ANTSError("Build registration template unsuccessful; see the log for details")

    logging.info("Built the registration template %s." % tmpl)
    return tmpl

Prompt:
Truncate a long log message.

import os
import logging
import envoy
from .ants_error import ANTSError

def create_template(metric, files):
    """
    Builds a template from the given image files.

    :param metric: the similarity metric
    :param files: the image files
    :return: the template file name
    """
    CMD = "buildtemplateparallel.sh -d 2 -c 2 -j 4 -d 2 -s {metric} -o {output} {files}"
    PREFIX = 'reg_'
    SUFFIX = 'template.nii.gz'

    tmpl = PREFIX + SUFFIX
    if os.path.exists(tmpl):
        logging.info("Registration template already exists: %s" % tmpl)
        return tmpl
    cmd = CMD.format(metric=metric.name, output=PREFIX, files=' '.join(files))
    logging.info("Building the %s registration template with the following command:" % tmpl)
    logging.info(cmd)
    r = envoy.run(cmd)
    if r.status_code:
        logging.error("Build registration template failed with error code %d" % r.status_code)
        logging.error(r.std_err)
        raise ANTSError("Build registration template unsuccessful; see the log for details")
    if not os.path.exists(tmpl):
        logging.error("Build registration template was not created.")
        raise ANTSError("Build registration template unsuccessful; see the log for details")

    logging.info("Built the registration template %s." % tmpl)
    return tmpl


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

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):
    """
    Tables cannot have data deleted from them and be altered in a single transaction,
    but we need the DELETEs to be atomic together. So we set atomic=False for the migration
    in general, and run the DELETEs in one transaction, and AlterField in another.
    """
    atomic = False

    dependencies = [
        ('zerver', '0231_add_archive_transaction_model'),
    ]

    operations = [
        migrations.RunSQL("""
        BEGIN;
        DELETE FROM zerver_archivedusermessage;
        DELETE FROM zerver_archivedreaction;
        DELETE FROM zerver_archivedsubmessage;
        DELETE FROM zerver_archivedattachment_messages;
        DELETE FROM zerver_archivedattachment;
        DELETE FROM zerver_archivedmessage;
        DELETE FROM zerver_archivetransaction;
        COMMIT;
        """),
        migrations.AlterField(
            model_name='archivedmessage',
            name='archive_transaction',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zerver.ArchiveTransaction'),
        ),
    ]

Response:
<REPLACE_OLD> django.db.models.deletion

class Migration(migrations.Migration):

 <REPLACE_NEW> django.db.models.deletion

class Migration(migrations.Migration):
    """
    Tables cannot have data deleted from them and be altered in a single transaction,
    but we need the DELETEs to be atomic together. So we set atomic=False for the migration
    in general, and run the DELETEs in one transaction, and AlterField in another.
    """
    atomic = False

 <REPLACE_END> <REPLACE_OLD> migrations.RunSQL("DELETE FROM zerver_archivedusermessage"),
        migrations.RunSQL("DELETE FROM zerver_archivedreaction"),
        migrations.RunSQL("DELETE FROM zerver_archivedsubmessage"),
        migrations.RunSQL("DELETE FROM zerver_archivedattachment"),
        migrations.RunSQL("DELETE FROM zerver_archivedattachment_messages"),
        migrations.RunSQL("DELETE FROM zerver_archivedmessage"),
        migrations.RunSQL("DELETE FROM zerver_archivetransaction"),
 <REPLACE_NEW> migrations.RunSQL("""
        BEGIN;
        DELETE FROM zerver_archivedusermessage;
        DELETE FROM zerver_archivedreaction;
        DELETE FROM zerver_archivedsubmessage;
        DELETE FROM zerver_archivedattachment_messages;
        DELETE FROM zerver_archivedattachment;
        DELETE FROM zerver_archivedmessage;
        DELETE FROM zerver_archivetransaction;
        COMMIT;
        """),
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):
    """
    Tables cannot have data deleted from them and be altered in a single transaction,
    but we need the DELETEs to be atomic together. So we set atomic=False for the migration
    in general, and run the DELETEs in one transaction, and AlterField in another.
    """
    atomic = False

    dependencies = [
        ('zerver', '0231_add_archive_transaction_model'),
    ]

    operations = [
        migrations.RunSQL("""
        BEGIN;
        DELETE FROM zerver_archivedusermessage;
        DELETE FROM zerver_archivedreaction;
        DELETE FROM zerver_archivedsubmessage;
        DELETE FROM zerver_archivedattachment_messages;
        DELETE FROM zerver_archivedattachment;
        DELETE FROM zerver_archivedmessage;
        DELETE FROM zerver_archivetransaction;
        COMMIT;
        """),
        migrations.AlterField(
            model_name='archivedmessage',
            name='archive_transaction',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zerver.ArchiveTransaction'),
        ),
    ]

Prompt:
retention: Fix migration making archive_transaction field not null.

DELETing from archive tables and ALTERing ArchivedMessage needs to be
split into separate transactions.

zerver_archivedattachment_messages needs to be cleared out before
zerver_archivedattachment.

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

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('zerver', '0231_add_archive_transaction_model'),
    ]

    operations = [
        migrations.RunSQL("DELETE FROM zerver_archivedusermessage"),
        migrations.RunSQL("DELETE FROM zerver_archivedreaction"),
        migrations.RunSQL("DELETE FROM zerver_archivedsubmessage"),
        migrations.RunSQL("DELETE FROM zerver_archivedattachment"),
        migrations.RunSQL("DELETE FROM zerver_archivedattachment_messages"),
        migrations.RunSQL("DELETE FROM zerver_archivedmessage"),
        migrations.RunSQL("DELETE FROM zerver_archivetransaction"),
        migrations.AlterField(
            model_name='archivedmessage',
            name='archive_transaction',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zerver.ArchiveTransaction'),
        ),
    ]


from importlib.metadata import version, PackageNotFoundError

try:
    __version__ = version('mizani')
except PackageNotFoundError:
    # package is not installed
    pass

Fix version number to check for mizani

Response:
<REPLACE_OLD> version('plotnine')
except <REPLACE_NEW> version('mizani')
except <REPLACE_END> <|endoftext|> from importlib.metadata import version, PackageNotFoundError

try:
    __version__ = version('mizani')
except PackageNotFoundError:
    # package is not installed
    pass

Prompt:
Fix version number to check for mizani

and not plotnine. Copypaste error!

from importlib.metadata import version, PackageNotFoundError

try:
    __version__ = version('plotnine')
except PackageNotFoundError:
    # package is not installed
    pass


Response:
<DELETE>   <DELETE_END> <DELETE>   <DELETE_END> <DELETE>   <DELETE_END> <DELETE>   <DELETE_END> <DELETE>     <DELETE_END> <DELETE>       <DELETE_END> <DELETE>       <DELETE_END> <DELETE>     <DELETE_END> <DELETE>       <DELETE_END> <DELETE>   <DELETE_END> <|endoftext|> #!/usr/bin/env python3

from common import *
import sys, signal

# Be naughty and ignore SIGTERM to simulate hanging child
signal.signal(signal.SIGTERM, signal.SIG_IGN)

# Start a server that listens for incoming connections
try:
  print_ok("child starting up on port %s" % sys.argv[1])
  s = TcpServer(int(sys.argv[1]))
  s.listen()
  while True:
    try:
      s.socket, _ = s.listener.accept()
      s.socket.settimeout(TIMEOUT)
    except:
      pass
finally:
  s.cleanup()

print_ok("child exiting")

Prompt:
Fix formatting in child sample to match other files

#!/usr/bin/env python3

from common import *
import sys, signal

# Be naughty and ignore SIGTERM to simulate hanging child
signal.signal(signal.SIGTERM, signal.SIG_IGN)

# Start a server that listens for incoming connections
try:
    print_ok("child starting up on port %s" % sys.argv[1])
    s = TcpServer(int(sys.argv[1]))
    s.listen()
    while True:
        try:
            s.socket, _ = s.listener.accept()
            s.socket.settimeout(TIMEOUT)
        except:
            pass
finally:
    s.cleanup()

print_ok("child exiting")


import warnings

from .loader import append_feed, delete_feed, overwrite_feed, list_feeds
from .schedule import Schedule

try:
    from ._version import version as __version__
except ImportError:
    warnings.warn("pygtfs should be installed for the version to work")
    __version__ = "0"

Response:
<REPLACE_OLD> from <REPLACE_NEW> import warnings

from <REPLACE_END> <REPLACE_OLD> Schedule
from <REPLACE_NEW> Schedule

try:
    from <REPLACE_END> <REPLACE_OLD> __version__
 <REPLACE_NEW> __version__
except ImportError:
    warnings.warn("pygtfs should be installed for the version to work")
    __version__ = "0"
 <REPLACE_END> <|endoftext|> import warnings

from .loader import append_feed, delete_feed, overwrite_feed, list_feeds
from .schedule import Schedule

try:
    from ._version import version as __version__
except ImportError:
    warnings.warn("pygtfs should be installed for the version to work")
    __version__ = "0"

Prompt:
Allow usage directly from the code (fix the _version import)

from .loader import append_feed, delete_feed, overwrite_feed, list_feeds
from .schedule import Schedule
from ._version import version as __version__


#/usr/bin/env python2.6
#
# $Id: setup.py 87 2010-07-01 18:01:03Z ver $

from distutils.core import setup

description = """
The Jersey core libraries provide common abstractions used by Jersey software.
"""

def getVersion():
    import os
    packageSeedFile = os.path.join("lib", "_version.py")
    ns = {"__name__": __name__, }
    execfile(packageSeedFile, ns)
    return ns["version"]

version = getVersion()

setup(
    name = "jersey",
    version = version.short(),

    description = "Jersey Core Libraries",
    long_description = description,

    author = "Oliver Gould", author_email = "ver@yahoo-inc.com",
    maintainer = "Jersey-Devel", maintainer_email = "jersey-devel@yahoo-inc.com",

    package_dir = {
        "jersey": "lib",
        },
    packages = [
        "jersey",
        "jersey.cases",
        ],
    py_modules = [
        "jersey._version",
        "jersey.cli",  "jersey.cases.test_cli",
        "jersey.inet", "jersey.cases.test_inet",
        "jersey.log",  "jersey.cases.test_log",
        ],

    provides = [
        "jersey",
        "jersey.cli",
        "jersey.log",
        ],
    requires = [
        "twisted (>=9.0.0)",
        ],

    )

Use lib/ instead of src/lib.

Use lib/ instead of src/lib.

Response:
<REPLACE_OLD> os.path.join("src", "lib", <REPLACE_NEW> os.path.join("lib", <REPLACE_END> <REPLACE_OLD> "src/lib",
 <REPLACE_NEW> "lib",
 <REPLACE_END> <|endoftext|> #/usr/bin/env python2.6
#
# $Id: setup.py 87 2010-07-01 18:01:03Z ver $

from distutils.core import setup

description = """
The Jersey core libraries provide common abstractions used by Jersey software.
"""

def getVersion():
    import os
    packageSeedFile = os.path.join("lib", "_version.py")
    ns = {"__name__": __name__, }
    execfile(packageSeedFile, ns)
    return ns["version"]

version = getVersion()

setup(
    name = "jersey",
    version = version.short(),

    description = "Jersey Core Libraries",
    long_description = description,

    author = "Oliver Gould", author_email = "ver@yahoo-inc.com",
    maintainer = "Jersey-Devel", maintainer_email = "jersey-devel@yahoo-inc.com",

    package_dir = {
        "jersey": "lib",
        },
    packages = [
        "jersey",
        "jersey.cases",
        ],
    py_modules = [
        "jersey._version",
        "jersey.cli",  "jersey.cases.test_cli",
        "jersey.inet", "jersey.cases.test_inet",
        "jersey.log",  "jersey.cases.test_log",
        ],

    provides = [
        "jersey",
        "jersey.cli",
        "jersey.log",
        ],
    requires = [
        "twisted (>=9.0.0)",
        ],

    )

Prompt:
Use lib/ instead of src/lib.

#/usr/bin/env python2.6
#
# $Id: setup.py 87 2010-07-01 18:01:03Z ver $

from distutils.core import setup

description = """
The Jersey core libraries provide common abstractions used by Jersey software.
"""

def getVersion():
    import os
    packageSeedFile = os.path.join("src", "lib", "_version.py")
    ns = {"__name__": __name__, }
    execfile(packageSeedFile, ns)
    return ns["version"]

version = getVersion()

setup(
    name = "jersey",
    version = version.short(),

    description = "Jersey Core Libraries",
    long_description = description,

    author = "Oliver Gould", author_email = "ver@yahoo-inc.com",
    maintainer = "Jersey-Devel", maintainer_email = "jersey-devel@yahoo-inc.com",

    package_dir = {
        "jersey": "src/lib",
        },
    packages = [
        "jersey",
        "jersey.cases",
        ],
    py_modules = [
        "jersey._version",
        "jersey.cli",  "jersey.cases.test_cli",
        "jersey.inet", "jersey.cases.test_inet",
        "jersey.log",  "jersey.cases.test_log",
        ],

    provides = [
        "jersey",
        "jersey.cli",
        "jersey.log",
        ],
    requires = [
        "twisted (>=9.0.0)",
        ],

    )


from __future__ import unicode_literals, print_function
import json
import pathlib
import random

import spacy
from spacy.pipeline import DependencyParser
from spacy.gold import GoldParse
from spacy.tokens import Doc

def train_parser(nlp, train_data, left_labels, right_labels):
    parser = DependencyParser.blank(
                                nlp.vocab,
                                left_labels=left_labels,
                                right_labels=right_labels,
                                features=nlp.defaults.parser_features)
    for itn in range(1000):
        random.shuffle(train_data)
        loss = 0
        for words, heads, deps in train_data:
            doc = nlp.make_doc(words)
            gold = GoldParse(doc, heads=heads, deps=deps)
            loss += parser.update(doc, gold)
    parser.model.end_training()
    return parser

def main(model_dir=None):
    if model_dir is not None:
        model_dir = pathlb.Path(model_dir)
        if not model_dir.exists():
            model_dir.mkdir()
        assert model_dir.isdir()

    nlp = spacy.load('en', tagger=False, parser=False, entity=False, vectors=False)
    nlp.make_doc = lambda words: Doc(nlp.vocab, zip(words, [True]*len(words)))

    train_data = [
        (
            ['They', 'trade',  'mortgage', '-', 'backed', 'securities', '.'],
            [1, 1, 4, 4, 5, 1, 1],
            ['nsubj', 'ROOT', 'compound', 'punct', 'nmod', 'dobj', 'punct']
        ),
        (
            ['I', 'like', 'London', 'and', 'Berlin', '.'],
            [1, 1, 1, 2, 2, 1],
            ['nsubj', 'ROOT', 'dobj', 'cc', 'conj', 'punct']
        )
    ]
    left_labels = set()
    right_labels = set()
    for _, heads, deps in train_data:
        for i, (head, dep) in enumerate(zip(heads, deps)):
            if i < head:
                left_labels.add(dep)
            elif i > head:
                right_labels.add(dep)
    parser = train_parser(nlp, train_data, sorted(left_labels), sorted(right_labels))

    doc = nlp.make_doc(['I', 'like', 'securities', '.'])
    with parser.step_through(doc) as state:
        while not state.is_final:
            action = state.predict()
            state.transition(action)
    #parser(doc)
    for word in doc:
        print(word.text, word.dep_, word.head.text)

    if model_dir is not None:
        with (model_dir / 'config.json').open('wb') as file_:
            json.dump(parser.cfg, file_)
        parser.model.dump(str(model_dir / 'model'))

if __name__ == '__main__':
    main()
    # I nsubj like
    # like ROOT like
    # securities dobj like
    # . cc securities

Add example for training parser

Add example for training parser

Response:
<REPLACE_OLD>  <REPLACE_NEW> from __future__ import unicode_literals, print_function
import json
import pathlib
import random

import spacy
from spacy.pipeline import DependencyParser
from spacy.gold import GoldParse
from spacy.tokens import Doc

def train_parser(nlp, train_data, left_labels, right_labels):
    parser = DependencyParser.blank(
                                nlp.vocab,
                                left_labels=left_labels,
                                right_labels=right_labels,
                                features=nlp.defaults.parser_features)
    for itn in range(1000):
        random.shuffle(train_data)
        loss = 0
        for words, heads, deps in train_data:
            doc = nlp.make_doc(words)
            gold = GoldParse(doc, heads=heads, deps=deps)
            loss += parser.update(doc, gold)
    parser.model.end_training()
    return parser

def main(model_dir=None):
    if model_dir is not None:
        model_dir = pathlb.Path(model_dir)
        if not model_dir.exists():
            model_dir.mkdir()
        assert model_dir.isdir()

    nlp = spacy.load('en', tagger=False, parser=False, entity=False, vectors=False)
    nlp.make_doc = lambda words: Doc(nlp.vocab, zip(words, [True]*len(words)))

    train_data = [
        (
            ['They', 'trade',  'mortgage', '-', 'backed', 'securities', '.'],
            [1, 1, 4, 4, 5, 1, 1],
            ['nsubj', 'ROOT', 'compound', 'punct', 'nmod', 'dobj', 'punct']
        ),
        (
            ['I', 'like', 'London', 'and', 'Berlin', '.'],
            [1, 1, 1, 2, 2, 1],
            ['nsubj', 'ROOT', 'dobj', 'cc', 'conj', 'punct']
        )
    ]
    left_labels = set()
    right_labels = set()
    for _, heads, deps in train_data:
        for i, (head, dep) in enumerate(zip(heads, deps)):
            if i < head:
                left_labels.add(dep)
            elif i > head:
                right_labels.add(dep)
    parser = train_parser(nlp, train_data, sorted(left_labels), sorted(right_labels))

    doc = nlp.make_doc(['I', 'like', 'securities', '.'])
    with parser.step_through(doc) as state:
        while not state.is_final:
            action = state.predict()
            state.transition(action)
    #parser(doc)
    for word in doc:
        print(word.text, word.dep_, word.head.text)

    if model_dir is not None:
        with (model_dir / 'config.json').open('wb') as file_:
            json.dump(parser.cfg, file_)
        parser.model.dump(str(model_dir / 'model'))

if __name__ == '__main__':
    main()
    # I nsubj like
    # like ROOT like
    # securities dobj like
    # . cc securities
 <REPLACE_END> <|endoftext|> from __future__ import unicode_literals, print_function
import json
import pathlib
import random

import spacy
from spacy.pipeline import DependencyParser
from spacy.gold import GoldParse
from spacy.tokens import Doc

def train_parser(nlp, train_data, left_labels, right_labels):
    parser = DependencyParser.blank(
                                nlp.vocab,
                                left_labels=left_labels,
                                right_labels=right_labels,
                                features=nlp.defaults.parser_features)
    for itn in range(1000):
        random.shuffle(train_data)
        loss = 0
        for words, heads, deps in train_data:
            doc = nlp.make_doc(words)
            gold = GoldParse(doc, heads=heads, deps=deps)
            loss += parser.update(doc, gold)
    parser.model.end_training()
    return parser

def main(model_dir=None):
    if model_dir is not None:
        model_dir = pathlb.Path(model_dir)
        if not model_dir.exists():
            model_dir.mkdir()
        assert model_dir.isdir()

    nlp = spacy.load('en', tagger=False, parser=False, entity=False, vectors=False)
    nlp.make_doc = lambda words: Doc(nlp.vocab, zip(words, [True]*len(words)))

    train_data = [
        (
            ['They', 'trade',  'mortgage', '-', 'backed', 'securities', '.'],
            [1, 1, 4, 4, 5, 1, 1],
            ['nsubj', 'ROOT', 'compound', 'punct', 'nmod', 'dobj', 'punct']
        ),
        (
            ['I', 'like', 'London', 'and', 'Berlin', '.'],
            [1, 1, 1, 2, 2, 1],
            ['nsubj', 'ROOT', 'dobj', 'cc', 'conj', 'punct']
        )
    ]
    left_labels = set()
    right_labels = set()
    for _, heads, deps in train_data:
        for i, (head, dep) in enumerate(zip(heads, deps)):
            if i < head:
                left_labels.add(dep)
            elif i > head:
                right_labels.add(dep)
    parser = train_parser(nlp, train_data, sorted(left_labels), sorted(right_labels))

    doc = nlp.make_doc(['I', 'like', 'securities', '.'])
    with parser.step_through(doc) as state:
        while not state.is_final:
            action = state.predict()
            state.transition(action)
    #parser(doc)
    for word in doc:
        print(word.text, word.dep_, word.head.text)

    if model_dir is not None:
        with (model_dir / 'config.json').open('wb') as file_:
            json.dump(parser.cfg, file_)
        parser.model.dump(str(model_dir / 'model'))

if __name__ == '__main__':
    main()
    # I nsubj like
    # like ROOT like
    # securities dobj like
    # . cc securities

Prompt: Add example for training parser


from django import template

from wagtail_personalisation.adapters import get_segment_adapter

register = template.Library()

@register.simple_tag
def filter_surveys_by_segments(surveys, request):
    """Filter out surveys not in user's segments."""
    user_segments = get_segment_adapter(request).get_segments()
    user_segments_ids = [s.id for s in user_segments]
    filtered_surveys = []

    for survey in surveys:
        if not hasattr(survey, 'segment_id') or not survey.segment_id \
                or survey.segment_id in user_segments_ids:
            filtered_surveys.append(survey)

    return filtered_surveys

Response:
<REPLACE_OLD> filetered_surveys <REPLACE_NEW> filtered_surveys <REPLACE_END> <REPLACE_OLD> survey.segment_id:
 <REPLACE_NEW> hasattr(survey, 'segment_id') or not survey.segment_id \
 <REPLACE_END> <DELETE> filetered_surveys.append(survey)
 <DELETE_END> <REPLACE_OLD>    elif <REPLACE_NEW> or <REPLACE_END> <REPLACE_OLD> filetered_surveys.append(survey)

 <REPLACE_NEW> filtered_surveys.append(survey)

 <REPLACE_END> <REPLACE_OLD> filetered_surveys
 <REPLACE_NEW> filtered_surveys
 <REPLACE_END> <|endoftext|> from django import template

from wagtail_personalisation.adapters import get_segment_adapter

register = template.Library()

@register.simple_tag
def filter_surveys_by_segments(surveys, request):
    """Filter out surveys not in user's segments."""
    user_segments = get_segment_adapter(request).get_segments()
    user_segments_ids = [s.id for s in user_segments]
    filtered_surveys = []

    for survey in surveys:
        if not hasattr(survey, 'segment_id') or not survey.segment_id \
                or survey.segment_id in user_segments_ids:
            filtered_surveys.append(survey)

    return filtered_surveys

Prompt:
Fix error when displaying other types of surveys

from django import template

from wagtail_personalisation.adapters import get_segment_adapter

register = template.Library()

@register.simple_tag
def filter_surveys_by_segments(surveys, request):
    """Filter out surveys not in user's segments."""
    user_segments = get_segment_adapter(request).get_segments()
    user_segments_ids = [s.id for s in user_segments]
    filetered_surveys = []

    for survey in surveys:
        if not survey.segment_id:
            filetered_surveys.append(survey)
        elif survey.segment_id in user_segments_ids:
            filetered_surveys.append(survey)

    return filetered_surveys


import sys
import os
import json
from optparse import make_option

from django.core.management.base import BaseCommand, CommandError

class Command(BaseCommand):
    help = 'Export Route(s) as GeoJSON'

    option_list = BaseCommand.option_list + (
        make_option('-o', dest='output_directory'),
    )

    def handle(self, *args, **kwargs):
        if len(args) == 0:
            raise CommandError('Please specify transportation id')

        output = kwargs.get('output_directory')

        tid = args[0]
        self._export(tid, output)

    def _export(self, tid, output=None):
        t = self._get_route_or_fail(tid)
        self._write(t, output)

    def _get_route_or_fail(self, tid):
        from angkot.route.models import Transportation

        t = Transportation.objects.filter(pk=tid, active=True)
        if len(t) == 0:
            raise CommandError('Transportation id not found: {}'.format(tid))

        return t[0]

    def _write(self, t, output=None):
        data = t.to_geojson()
        data['properties']['legal'] = dict(
            license='ODbL 1.0',
            copyright='© AngkotWebId Contributors')
        geojson = json.dumps(data, indent=4)

        out = self._get_output(t, output)
        out.write(geojson)
        out.close()

    def _get_output(self, t, output=None):
        if output is None:
            return sys.stdout

        fname = '{} - {} - {} - {} - {}.json'.format(t.id, t.province, t.city, t.company, t.number)
        path = os.path.join(output, fname)
        return open(path, 'w')

Add script to export route to GeoJSON data

Response:
<REPLACE_OLD>  <REPLACE_NEW> import sys
import os
import json
from optparse import make_option

from django.core.management.base import BaseCommand, CommandError

class Command(BaseCommand):
    help = 'Export Route(s) as GeoJSON'

    option_list = BaseCommand.option_list + (
        make_option('-o', dest='output_directory'),
    )

    def handle(self, *args, **kwargs):
        if len(args) == 0:
            raise CommandError('Please specify transportation id')

        output = kwargs.get('output_directory')

        tid = args[0]
        self._export(tid, output)

    def _export(self, tid, output=None):
        t = self._get_route_or_fail(tid)
        self._write(t, output)

    def _get_route_or_fail(self, tid):
        from angkot.route.models import Transportation

        t = Transportation.objects.filter(pk=tid, active=True)
        if len(t) == 0:
            raise CommandError('Transportation id not found: {}'.format(tid))

        return t[0]

    def _write(self, t, output=None):
        data = t.to_geojson()
        data['properties']['legal'] = dict(
            license='ODbL 1.0',
            copyright='© AngkotWebId Contributors')
        geojson = json.dumps(data, indent=4)

        out = self._get_output(t, output)
        out.write(geojson)
        out.close()

    def _get_output(self, t, output=None):
        if output is None:
            return sys.stdout

        fname = '{} - {} - {} - {} - {}.json'.format(t.id, t.province, t.city, t.company, t.number)
        path = os.path.join(output, fname)
        return open(path, 'w')

 <REPLACE_END> <|endoftext|> import sys
import os
import json
from optparse import make_option

from django.core.management.base import BaseCommand, CommandError

class Command(BaseCommand):
    help = 'Export Route(s) as GeoJSON'

    option_list = BaseCommand.option_list + (
        make_option('-o', dest='output_directory'),
    )

    def handle(self, *args, **kwargs):
        if len(args) == 0:
            raise CommandError('Please specify transportation id')

        output = kwargs.get('output_directory')

        tid = args[0]
        self._export(tid, output)

    def _export(self, tid, output=None):
        t = self._get_route_or_fail(tid)
        self._write(t, output)

    def _get_route_or_fail(self, tid):
        from angkot.route.models import Transportation

        t = Transportation.objects.filter(pk=tid, active=True)
        if len(t) == 0:
            raise CommandError('Transportation id not found: {}'.format(tid))

        return t[0]

    def _write(self, t, output=None):
        data = t.to_geojson()
        data['properties']['legal'] = dict(
            license='ODbL 1.0',
            copyright='© AngkotWebId Contributors')
        geojson = json.dumps(data, indent=4)

        out = self._get_output(t, output)
        out.write(geojson)
        out.close()

    def _get_output(self, t, output=None):
        if output is None:
            return sys.stdout

        fname = '{} - {} - {} - {} - {}.json'.format(t.id, t.province, t.city, t.company, t.number)
        path = os.path.join(output, fname)
        return open(path, 'w')

Prompt: Add script to export route to GeoJSON data


from setuptools import setup

def readme():
    with open('README.rst') as f:
        return f.read()

setup(name='savu',
      version='0.1.1',
      description='Savu Python Tomography Pipeline',
      long_description=readme(),
      classifiers=[
        'Development Status :: 1 - Planning',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: Apache Software License',
        'Natural Language :: English',
        'Programming Language :: Python :: 2.7',
        'Topic :: Scientific/Engineering'
      ],
      author='Mark Basham',
      author_email='scientificsoftware@diamond.ac.uk',
      license='Apache License, Version 2.0',
      packages=['savu',
                'savu.core',
                'savu.data',
                'savu.mpi_test',
                'savu.mpi_test.dls',
                'savu.plugins',
                'savu.test'],
      include_package_data=True,
      zip_safe=False)

Response:
<REPLACE_OLD> version='0.1',
 <REPLACE_NEW> version='0.1.1',
 <REPLACE_END> <|endoftext|> from setuptools import setup

def readme():
    with open('README.rst') as f:
        return f.read()

setup(name='savu',
      version='0.1.1',
      description='Savu Python Tomography Pipeline',
      long_description=readme(),
      classifiers=[
        'Development Status :: 1 - Planning',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: Apache Software License',
        'Natural Language :: English',
        'Programming Language :: Python :: 2.7',
        'Topic :: Scientific/Engineering'
      ],
      author='Mark Basham',
      author_email='scientificsoftware@diamond.ac.uk',
      license='Apache License, Version 2.0',
      packages=['savu',
                'savu.core',
                'savu.data',
                'savu.mpi_test',
                'savu.mpi_test.dls',
                'savu.plugins',
                'savu.test'],
      include_package_data=True,
      zip_safe=False)

Prompt:
Update to version 0.1.1 for the next push
from setuptools import setup

def readme():
    with open('README.rst') as f:
        return f.read()

setup(name='savu',
      version='0.1',
      description='Savu Python Tomography Pipeline',
      long_description=readme(),
      classifiers=[
        'Development Status :: 1 - Planning',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: Apache Software License',
        'Natural Language :: English',
        'Programming Language :: Python :: 2.7',
        'Topic :: Scientific/Engineering'
      ],
      author='Mark Basham',
      author_email='scientificsoftware@diamond.ac.uk',
      license='Apache License, Version 2.0',
      packages=['savu',
                'savu.core',
                'savu.data',
                'savu.mpi_test',
                'savu.mpi_test.dls',
                'savu.plugins',
                'savu.test'],
      include_package_data=True,
      zip_safe=False)


from firedrake import (SpatialCoordinate, dot, cross, sqrt, atan_2,
                       exp, as_vector, Constant, acos)
import numpy as np

class Gaussian(object):

    def __init__(self,
                 mesh,
                 dir_from_center,
                 radial_dist,
                 sigma_theta,
                 sigma_r,
                 amplitude=1):

        self._mesh = mesh
        self._n0 = dir_from_center
        self._r0 = radial_dist
        self._sigma_theta = sigma_theta
        self._sigma_r = sigma_r
        self._amp = amplitude

        self.x = SpatialCoordinate(mesh)

    @property
    def r(self):
        x = self.x
        return sqrt(x[0]**2 + x[1]**2 + x[2]**2)

    @property
    def theta(self):
        x = self.x
        n0 = self._n0
        return acos(dot(x, n0) / abs(dot(x, n0)))

    @property
    def r_expr(self):
        r = self.r
        r0 = self._r0
        return r - r0

    @property
    def expression(self):
        A = self._amp
        theta = self.theta
        R = self.r_expr
        sigma_theta = self._sigma_theta
        sigma_r = self._sigma_r
        return A*exp(-0.5*((theta/sigma_theta)**2 + (R/sigma_r)**2))

class MultipleGaussians(object):

    def __init__(self, n_gaussians, r_earth, thickness, seed=2097152):

        self._N = n_gaussians
        self._R = r_earth
        self._H = thickness
        self._seed = seed
        self._generate_random_vars()

    def _generate_random_vars(self):
        np.random.rand(self._seed)
        ns = []
        rs = []
        for i in range(self._N):
            nrm = 0.0

            while (nrm < 0.5) or (nrm > 1.0):
                n = 2*np.random.rand(3) - 1.0
                nrm = np.linalg.norm(n)

            ns.append(as_vector(list(n)))
            rs.append(Constant(self._R + self._H * np.random.rand()))

        self._random_Ns = ns
        self._random_Rs = rs

    def expression(self, mesh):

        gs = []
        for i, (n, r0) in enumerate(zip(self._random_Ns, self._random_Rs)):
            sigma_theta = 1.0 - 0.5 * (i / self._N)
            sigma_r = (1.0 - 0.5 * (i / self._N)) * self._H
            amplitude = 1.0
            g = Gaussian(mesh, n, r0, sigma_theta, sigma_r, amplitude)
            gs.append(g.expression)

        return sum(gs)

Set up object to create random pressure field

Response:
<REPLACE_OLD>  <REPLACE_NEW> from firedrake import (SpatialCoordinate, dot, cross, sqrt, atan_2,
                       exp, as_vector, Constant, acos)
import numpy as np

class Gaussian(object):

    def __init__(self,
                 mesh,
                 dir_from_center,
                 radial_dist,
                 sigma_theta,
                 sigma_r,
                 amplitude=1):

        self._mesh = mesh
        self._n0 = dir_from_center
        self._r0 = radial_dist
        self._sigma_theta = sigma_theta
        self._sigma_r = sigma_r
        self._amp = amplitude

        self.x = SpatialCoordinate(mesh)

    @property
    def r(self):
        x = self.x
        return sqrt(x[0]**2 + x[1]**2 + x[2]**2)

    @property
    def theta(self):
        x = self.x
        n0 = self._n0
        return acos(dot(x, n0) / abs(dot(x, n0)))

    @property
    def r_expr(self):
        r = self.r
        r0 = self._r0
        return r - r0

    @property
    def expression(self):
        A = self._amp
        theta = self.theta
        R = self.r_expr
        sigma_theta = self._sigma_theta
        sigma_r = self._sigma_r
        return A*exp(-0.5*((theta/sigma_theta)**2 + (R/sigma_r)**2))

class MultipleGaussians(object):

    def __init__(self, n_gaussians, r_earth, thickness, seed=2097152):

        self._N = n_gaussians
        self._R = r_earth
        self._H = thickness
        self._seed = seed
        self._generate_random_vars()

    def _generate_random_vars(self):
        np.random.rand(self._seed)
        ns = []
        rs = []
        for i in range(self._N):
            nrm = 0.0

            while (nrm < 0.5) or (nrm > 1.0):
                n = 2*np.random.rand(3) - 1.0
                nrm = np.linalg.norm(n)

            ns.append(as_vector(list(n)))
            rs.append(Constant(self._R + self._H * np.random.rand()))

        self._random_Ns = ns
        self._random_Rs = rs

    def expression(self, mesh):

        gs = []
        for i, (n, r0) in enumerate(zip(self._random_Ns, self._random_Rs)):
            sigma_theta = 1.0 - 0.5 * (i / self._N)
            sigma_r = (1.0 - 0.5 * (i / self._N)) * self._H
            amplitude = 1.0
            g = Gaussian(mesh, n, r0, sigma_theta, sigma_r, amplitude)
            gs.append(g.expression)

        return sum(gs)
 <REPLACE_END> <|endoftext|> from firedrake import (SpatialCoordinate, dot, cross, sqrt, atan_2,
                       exp, as_vector, Constant, acos)
import numpy as np

class Gaussian(object):

    def __init__(self,
                 mesh,
                 dir_from_center,
                 radial_dist,
                 sigma_theta,
                 sigma_r,
                 amplitude=1):

        self._mesh = mesh
        self._n0 = dir_from_center
        self._r0 = radial_dist
        self._sigma_theta = sigma_theta
        self._sigma_r = sigma_r
        self._amp = amplitude

        self.x = SpatialCoordinate(mesh)

    @property
    def r(self):
        x = self.x
        return sqrt(x[0]**2 + x[1]**2 + x[2]**2)

    @property
    def theta(self):
        x = self.x
        n0 = self._n0
        return acos(dot(x, n0) / abs(dot(x, n0)))

    @property
    def r_expr(self):
        r = self.r
        r0 = self._r0
        return r - r0

    @property
    def expression(self):
        A = self._amp
        theta = self.theta
        R = self.r_expr
        sigma_theta = self._sigma_theta
        sigma_r = self._sigma_r
        return A*exp(-0.5*((theta/sigma_theta)**2 + (R/sigma_r)**2))

class MultipleGaussians(object):

    def __init__(self, n_gaussians, r_earth, thickness, seed=2097152):

        self._N = n_gaussians
        self._R = r_earth
        self._H = thickness
        self._seed = seed
        self._generate_random_vars()

    def _generate_random_vars(self):
        np.random.rand(self._seed)
        ns = []
        rs = []
        for i in range(self._N):
            nrm = 0.0

            while (nrm < 0.5) or (nrm > 1.0):
                n = 2*np.random.rand(3) - 1.0
                nrm = np.linalg.norm(n)

            ns.append(as_vector(list(n)))
            rs.append(Constant(self._R + self._H * np.random.rand()))

        self._random_Ns = ns
        self._random_Rs = rs

    def expression(self, mesh):

        gs = []
        for i, (n, r0) in enumerate(zip(self._random_Ns, self._random_Rs)):
            sigma_theta = 1.0 - 0.5 * (i / self._N)
            sigma_r = (1.0 - 0.5 * (i / self._N)) * self._H
            amplitude = 1.0
            g = Gaussian(mesh, n, r0, sigma_theta, sigma_r, amplitude)
            gs.append(g.expression)

        return sum(gs)

Prompt: Set up object to create random pressure field


from setuptools import setup
import os

#Function to read README
def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    name='clipboard_memo',
    version='0.1',
    description='A command-line clipboard manager',
    long_description=read('README.rst'),
    url='http://github.com/arafsheikh/clipboard-memo',
    author='Sheikh Araf',
    author_email='arafsheikh@rocketmail.com',
    license='MIT',
    keywords='clipboard memo manager command-line CLI',
    include_package_data=True,
    entry_points='''
        [console_scripts]
        cmemo=clipboard_memo:main
        cmemo_direct=clipboard_memo:direct_save
    ''',
    py_modules=['clipboard_memo'],
    install_requires=[
        'pyperclip',
    ],
)

Use README.rst for long description

Use README.rst for long description

Response:
<REPLACE_OLD> long_description=read('README.md'),
 <REPLACE_NEW> long_description=read('README.rst'),
 <REPLACE_END> <|endoftext|> from setuptools import setup
import os

#Function to read README
def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    name='clipboard_memo',
    version='0.1',
    description='A command-line clipboard manager',
    long_description=read('README.rst'),
    url='http://github.com/arafsheikh/clipboard-memo',
    author='Sheikh Araf',
    author_email='arafsheikh@rocketmail.com',
    license='MIT',
    keywords='clipboard memo manager command-line CLI',
    include_package_data=True,
    entry_points='''
        [console_scripts]
        cmemo=clipboard_memo:main
        cmemo_direct=clipboard_memo:direct_save
    ''',
    py_modules=['clipboard_memo'],
    install_requires=[
        'pyperclip',
    ],
)

Prompt:
Use README.rst for long description

from setuptools import setup
import os

#Function to read README
def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    name='clipboard_memo',
    version='0.1',
    description='A command-line clipboard manager',
    long_description=read('README.md'),
    url='http://github.com/arafsheikh/clipboard-memo',
    author='Sheikh Araf',
    author_email='arafsheikh@rocketmail.com',
    license='MIT',
    keywords='clipboard memo manager command-line CLI',
    include_package_data=True,
    entry_points='''
        [console_scripts]
        cmemo=clipboard_memo:main
        cmemo_direct=clipboard_memo:direct_save
    ''',
    py_modules=['clipboard_memo'],
    install_requires=[
        'pyperclip',
    ],
)


from nose.tools import assert_true
from ..examples.sample_data import (temperature_ramp, multisource_event,
                                    image_and_scalar)
from metadatastore.api import Document

def run_example(example):
    events = example.run()
    assert_true(isinstance(events, list))
    assert_true(isinstance(events[0], Document))

def test_examples():
    for example in [temperature_ramp, multisource_event, image_and_scalar]:
        yield run_example, example

Use generator test for examples.

REF: Use generator test for examples.

Response:
<INSERT> from nose.tools <INSERT_END> <REPLACE_OLD> unittest
from <REPLACE_NEW> assert_true
from <REPLACE_END> <REPLACE_OLD> Document

class CommonSampleDataTests(object):
 <REPLACE_NEW> Document

def run_example(example):
 <REPLACE_END> <REPLACE_OLD> def setUp(self):
 <REPLACE_NEW> events = example.run()
    assert_true(isinstance(events, list))
    assert_true(isinstance(events[0], Document))

def test_examples():
    for example in [temperature_ramp, multisource_event, image_and_scalar]:
 <REPLACE_END> <REPLACE_OLD> pass

    def test_basic_usage(self):
        events = self.example.run()

        # check expected types
        self.assertTrue(isinstance(events, list))
        self.assertTrue(isinstance(events[0], Document))

class TestTemperatureRamp(CommonSampleDataTests, unittest.TestCase):

    def setUp(self):
        self.example = temperature_ramp

class TestMultisourceEvent(CommonSampleDataTests, unittest.TestCase):

    def setUp(self):
        self.example = multisource_event

class TestImageAndScalar(CommonSampleDataTests, unittest.TestCase):

    def setUp(self):
        self.example = image_and_scalar
 <REPLACE_NEW> yield run_example, example
 <REPLACE_END> <|endoftext|> from nose.tools import assert_true
from ..examples.sample_data import (temperature_ramp, multisource_event,
                                    image_and_scalar)
from metadatastore.api import Document

def run_example(example):
    events = example.run()
    assert_true(isinstance(events, list))
    assert_true(isinstance(events[0], Document))

def test_examples():
    for example in [temperature_ramp, multisource_event, image_and_scalar]:
        yield run_example, example

Prompt:
REF: Use generator test for examples.

import unittest
from ..examples.sample_data import (temperature_ramp, multisource_event,
                                    image_and_scalar)
from metadatastore.api import Document

class CommonSampleDataTests(object):
    def setUp(self):
        pass

    def test_basic_usage(self):
        events = self.example.run()

        # check expected types
        self.assertTrue(isinstance(events, list))
        self.assertTrue(isinstance(events[0], Document))

class TestTemperatureRamp(CommonSampleDataTests, unittest.TestCase):

    def setUp(self):
        self.example = temperature_ramp

class TestMultisourceEvent(CommonSampleDataTests, unittest.TestCase):

    def setUp(self):
        self.example = multisource_event

class TestImageAndScalar(CommonSampleDataTests, unittest.TestCase):

    def setUp(self):
        self.example = image_and_scalar


# -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-09-11 15:24
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('data_interfaces', '0018_check_for_rule_migration'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='automaticupdateaction',
            name='rule',
        ),
        migrations.RemoveField(
            model_name='automaticupdaterulecriteria',
            name='rule',
        ),
        migrations.DeleteModel(
            name='AutomaticUpdateAction',
        ),
        migrations.DeleteModel(
            name='AutomaticUpdateRuleCriteria',
        ),
    ]

Add migration to remove old rule models

Add migration to remove old rule models

Response:
<INSERT> # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-09-11 15:24
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import migrations

class Migration(migrations.Migration):

 <INSERT_END> <INSERT>   dependencies = [
        ('data_interfaces', '0018_check_for_rule_migration'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='automaticupdateaction',
            name='rule',
        ),
        migrations.RemoveField(
            model_name='automaticupdaterulecriteria',
            name='rule',
        ),
        migrations.DeleteModel(
            name='AutomaticUpdateAction',
        ),
        migrations.DeleteModel(
            name='AutomaticUpdateRuleCriteria',
        ),
    ]
 <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-09-11 15:24
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('data_interfaces', '0018_check_for_rule_migration'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='automaticupdateaction',
            name='rule',
        ),
        migrations.RemoveField(
            model_name='automaticupdaterulecriteria',
            name='rule',
        ),
        migrations.DeleteModel(
            name='AutomaticUpdateAction',
        ),
        migrations.DeleteModel(
            name='AutomaticUpdateRuleCriteria',
        ),
    ]

Prompt: Add migration to remove old rule models


# -*- coding: utf-8 -*-
'''module for unit test and task for CI'''
import sys
import unittest

from yatest import testpost, testpage, testutility, testconfig, testgenerator, testpostmanager

if __name__ == '__main__':
    all_test_suites = []
    all_test_suites.append(testpost.get_test_suites())
    all_test_suites.append(testpage.get_test_suites())
    all_test_suites.append(testutility.get_test_suites())
    all_test_suites.append(testconfig.get_test_suites())
    all_test_suites.append(testgenerator.get_test_suites())
    all_test_suites.append(testpostmanager.get_test_suites())

    alltests = unittest.TestSuite(all_test_suites)

    status = not unittest.TextTestRunner(verbosity=2).run(alltests).wasSuccessful()
    sys.exit(status)

Response:
<REPLACE_OLD> testconfig

if <REPLACE_NEW> testconfig, testgenerator, testpostmanager

if <REPLACE_END> <REPLACE_OLD> all_test_suites.append(testconfig.get_test_suites())

 <REPLACE_NEW> all_test_suites.append(testconfig.get_test_suites())
    all_test_suites.append(testgenerator.get_test_suites())
    all_test_suites.append(testpostmanager.get_test_suites())

 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
'''module for unit test and task for CI'''
import sys
import unittest

from yatest import testpost, testpage, testutility, testconfig, testgenerator, testpostmanager

if __name__ == '__main__':
    all_test_suites = []
    all_test_suites.append(testpost.get_test_suites())
    all_test_suites.append(testpage.get_test_suites())
    all_test_suites.append(testutility.get_test_suites())
    all_test_suites.append(testconfig.get_test_suites())
    all_test_suites.append(testgenerator.get_test_suites())
    all_test_suites.append(testpostmanager.get_test_suites())

    alltests = unittest.TestSuite(all_test_suites)

    status = not unittest.TextTestRunner(verbosity=2).run(alltests).wasSuccessful()
    sys.exit(status)

Prompt:
Add test cases for module post_manager, refactor part of class PostManager and update TODO list.

# -*- coding: utf-8 -*-
'''module for unit test and task for CI'''
import sys
import unittest

from yatest import testpost, testpage, testutility, testconfig

if __name__ == '__main__':
    all_test_suites = []
    all_test_suites.append(testpost.get_test_suites())
    all_test_suites.append(testpage.get_test_suites())
    all_test_suites.append(testutility.get_test_suites())
    all_test_suites.append(testconfig.get_test_suites())

    alltests = unittest.TestSuite(all_test_suites)

    status = not unittest.TextTestRunner(verbosity=2).run(alltests).wasSuccessful()
    sys.exit(status)


VERSION = (1, 4, 6, 'alpha', 0)

def get_version(version=None):
    """Derives a PEP386-compliant version number from VERSION."""
    if version is None:
        version = VERSION
    assert len(version) == 5
    assert version[3] in ('alpha', 'beta', 'rc', 'final')

    # Now build the two parts of the version number:
    # main = X.Y[.Z]
    # sub = .devN - for pre-alpha releases
    #     | {a|b|c}N - for alpha, beta and rc releases

    parts = 2 if version[2] == 0 else 3
    main = '.'.join(str(x) for x in version[:parts])

    sub = ''
    if version[3] == 'alpha' and version[4] == 0:
        # At the toplevel, this would cause an import loop.
        from django.utils.version import get_svn_revision
        svn_revision = get_svn_revision()[4:]
        if svn_revision != 'unknown':
            sub = '.dev%s' % svn_revision

    elif version[3] != 'final':
        mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
        sub = mapping[version[3]] + str(version[4])

    return main + sub

Response:
<REPLACE_OLD> 5, 'final', <REPLACE_NEW> 6, 'alpha', <REPLACE_END> <|endoftext|> VERSION = (1, 4, 6, 'alpha', 0)

def get_version(version=None):
    """Derives a PEP386-compliant version number from VERSION."""
    if version is None:
        version = VERSION
    assert len(version) == 5
    assert version[3] in ('alpha', 'beta', 'rc', 'final')

    # Now build the two parts of the version number:
    # main = X.Y[.Z]
    # sub = .devN - for pre-alpha releases
    #     | {a|b|c}N - for alpha, beta and rc releases

    parts = 2 if version[2] == 0 else 3
    main = '.'.join(str(x) for x in version[:parts])

    sub = ''
    if version[3] == 'alpha' and version[4] == 0:
        # At the toplevel, this would cause an import loop.
        from django.utils.version import get_svn_revision
        svn_revision = get_svn_revision()[4:]
        if svn_revision != 'unknown':
            sub = '.dev%s' % svn_revision

    elif version[3] != 'final':
        mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
        sub = mapping[version[3]] + str(version[4])

    return main + sub

Prompt:
[1.4.x] Bump version to no longer claim to be 1.4.5 final.

VERSION = (1, 4, 5, 'final', 0)

def get_version(version=None):
    """Derives a PEP386-compliant version number from VERSION."""
    if version is None:
        version = VERSION
    assert len(version) == 5
    assert version[3] in ('alpha', 'beta', 'rc', 'final')

    # Now build the two parts of the version number:
    # main = X.Y[.Z]
    # sub = .devN - for pre-alpha releases
    #     | {a|b|c}N - for alpha, beta and rc releases

    parts = 2 if version[2] == 0 else 3
    main = '.'.join(str(x) for x in version[:parts])

    sub = ''
    if version[3] == 'alpha' and version[4] == 0:
        # At the toplevel, this would cause an import loop.
        from django.utils.version import get_svn_revision
        svn_revision = get_svn_revision()[4:]
        if svn_revision != 'unknown':
            sub = '.dev%s' % svn_revision

    elif version[3] != 'final':
        mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
        sub = mapping[version[3]] + str(version[4])

    return main + sub