"""Test IPython.core.logger"""

import nose.tools as nt

_ip = get_ipython()

def test_logstart_inaccessible_file():
    try:
        _ip.logger.logstart(logfname="/")   # Opening that filename will fail.
    except IOError:
        pass
    else:
        nt.assert_true(False)           # The try block should never pass.

    try:
        _ip.run_cell("a=1")                 # Check it doesn't try to log this
    finally:
        _ip.logger.log_active = False  # If this fails, don't let later tests fail

Add test that, if we failed to open the log file, we don't try to write to it.

Response:
<INSERT> """Test IPython.core.logger"""

import nose.tools as nt

_ip = get_ipython()

def test_logstart_inaccessible_file():
 <INSERT_END> <INSERT>   try:
        _ip.logger.logstart(logfname="/")   # Opening that filename will fail.
    except IOError:
        pass
    else:
        nt.assert_true(False)           # The try block should never pass.

    try:
        _ip.run_cell("a=1")                 # Check it doesn't try to log this
    finally:
        _ip.logger.log_active = False  # If this fails, don't let later tests fail

 <INSERT_END> <|endoftext|> """Test IPython.core.logger"""

import nose.tools as nt

_ip = get_ipython()

def test_logstart_inaccessible_file():
    try:
        _ip.logger.logstart(logfname="/")   # Opening that filename will fail.
    except IOError:
        pass
    else:
        nt.assert_true(False)           # The try block should never pass.

    try:
        _ip.run_cell("a=1")                 # Check it doesn't try to log this
    finally:
        _ip.logger.log_active = False  # If this fails, don't let later tests fail

Prompt: Add test that, if we failed to open the log file, we don't try to write to it.


from django.core.cache import cache
from django.test import SimpleTestCase

from ormcache.signals import cache_hit, cache_missed, cache_invalidated
from ormcache.tests.testapp.models import CachedDummyModel

class SignalsTestCase(SimpleTestCase):

    def setUp(self):
        self.signal_called = False
        self.instance_pk = CachedDummyModel.objects.create().pk
        cache.clear()

    def _signal_callback(self, sender, signal):
        self.signal_called = True

    def test_cache_hit_signal(self):
        cache_hit.connect(self._signal_callback)

        CachedDummyModel.objects.get(pk=self.instance_pk)  # miss
        self.assertFalse(self.signal_called)
        CachedDummyModel.objects.get(pk=self.instance_pk)  # hit
        self.assertTrue(self.signal_called)

    def test_cache_missed_signal(self):
        cache_missed.connect(self._signal_callback)

        CachedDummyModel.objects.get(pk=self.instance_pk)  # miss
        self.assertTrue(self.signal_called)

    def test_cache_invalidated_signal(self):
        cache_invalidated.connect(self._signal_callback)

        instance = CachedDummyModel.objects.get(pk=self.instance_pk)  # miss
        self.assertFalse(self.signal_called)
        instance.title = "hello"
        instance.save()  # invalidate
        self.assertTrue(self.signal_called)

Add tests for the signals

Add tests for the signals

Response:
<REPLACE_OLD>  <REPLACE_NEW> from django.core.cache import cache
from django.test import SimpleTestCase

from ormcache.signals import cache_hit, cache_missed, cache_invalidated
from ormcache.tests.testapp.models import CachedDummyModel

class SignalsTestCase(SimpleTestCase):

    def setUp(self):
        self.signal_called = False
        self.instance_pk = CachedDummyModel.objects.create().pk
        cache.clear()

    def _signal_callback(self, sender, signal):
        self.signal_called = True

    def test_cache_hit_signal(self):
        cache_hit.connect(self._signal_callback)

        CachedDummyModel.objects.get(pk=self.instance_pk)  # miss
        self.assertFalse(self.signal_called)
        CachedDummyModel.objects.get(pk=self.instance_pk)  # hit
        self.assertTrue(self.signal_called)

    def test_cache_missed_signal(self):
        cache_missed.connect(self._signal_callback)

        CachedDummyModel.objects.get(pk=self.instance_pk)  # miss
        self.assertTrue(self.signal_called)

    def test_cache_invalidated_signal(self):
        cache_invalidated.connect(self._signal_callback)

        instance = CachedDummyModel.objects.get(pk=self.instance_pk)  # miss
        self.assertFalse(self.signal_called)
        instance.title = "hello"
        instance.save()  # invalidate
        self.assertTrue(self.signal_called)
 <REPLACE_END> <|endoftext|> from django.core.cache import cache
from django.test import SimpleTestCase

from ormcache.signals import cache_hit, cache_missed, cache_invalidated
from ormcache.tests.testapp.models import CachedDummyModel

class SignalsTestCase(SimpleTestCase):

    def setUp(self):
        self.signal_called = False
        self.instance_pk = CachedDummyModel.objects.create().pk
        cache.clear()

    def _signal_callback(self, sender, signal):
        self.signal_called = True

    def test_cache_hit_signal(self):
        cache_hit.connect(self._signal_callback)

        CachedDummyModel.objects.get(pk=self.instance_pk)  # miss
        self.assertFalse(self.signal_called)
        CachedDummyModel.objects.get(pk=self.instance_pk)  # hit
        self.assertTrue(self.signal_called)

    def test_cache_missed_signal(self):
        cache_missed.connect(self._signal_callback)

        CachedDummyModel.objects.get(pk=self.instance_pk)  # miss
        self.assertTrue(self.signal_called)

    def test_cache_invalidated_signal(self):
        cache_invalidated.connect(self._signal_callback)

        instance = CachedDummyModel.objects.get(pk=self.instance_pk)  # miss
        self.assertFalse(self.signal_called)
        instance.title = "hello"
        instance.save()  # invalidate
        self.assertTrue(self.signal_called)

Prompt: Add tests for the signals


from threading import Thread, Event

try:
    from queue import Queue
except ImportError:
    from Queue import Queue

class Timer(Thread):
    def __init__(self, interval, function, args=[], kwargs={}):
        super(Timer, self).__init__()
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.finished = Event()

    def cancel(self):
        self.finished.set()

    def run(self):
        self.finished.wait(self.interval)
        if not self.finished.is_set():
            self.function(*self.args, **self.kwargs)
        self.finished.set()

class EventSpooler(object):
    def __init__(self, cooldown, callback):
        self.cooldown = cooldown
        self.callback = callback
        self.inbox = Queue()
        self.outbox = Queue()

    def enqueue(self, event):
        self.inbox.put(event)
        Timer(self.cooldown, self.process).start()

    def process(self):
        self.outbox.put(self.inbox.get())
        if self.inbox.empty():
            events = []
            while not self.outbox.empty():
                events.append(self.outbox.get())
            self.callback(events)

Response:
<REPLACE_OLD> # -*- coding: utf-8

from multiprocessing <REPLACE_NEW> from threading <REPLACE_END> <REPLACE_OLD> Queue, Process, Event

class Timer(Process):
 <REPLACE_NEW> Thread, Event

try:
    from queue import Queue
except ImportError:
    from Queue import Queue

class Timer(Thread):
 <REPLACE_END> <|endoftext|> from threading import Thread, Event

try:
    from queue import Queue
except ImportError:
    from Queue import Queue

class Timer(Thread):
    def __init__(self, interval, function, args=[], kwargs={}):
        super(Timer, self).__init__()
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.finished = Event()

    def cancel(self):
        self.finished.set()

    def run(self):
        self.finished.wait(self.interval)
        if not self.finished.is_set():
            self.function(*self.args, **self.kwargs)
        self.finished.set()

class EventSpooler(object):
    def __init__(self, cooldown, callback):
        self.cooldown = cooldown
        self.callback = callback
        self.inbox = Queue()
        self.outbox = Queue()

    def enqueue(self, event):
        self.inbox.put(event)
        Timer(self.cooldown, self.process).start()

    def process(self):
        self.outbox.put(self.inbox.get())
        if self.inbox.empty():
            events = []
            while not self.outbox.empty():
                events.append(self.outbox.get())
            self.callback(events)

Prompt:
Use threading instead of multiprocessing.

# -*- coding: utf-8

from multiprocessing import Queue, Process, Event

class Timer(Process):
    def __init__(self, interval, function, args=[], kwargs={}):
        super(Timer, self).__init__()
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.finished = Event()

    def cancel(self):
        self.finished.set()

    def run(self):
        self.finished.wait(self.interval)
        if not self.finished.is_set():
            self.function(*self.args, **self.kwargs)
        self.finished.set()

class EventSpooler(object):
    def __init__(self, cooldown, callback):
        self.cooldown = cooldown
        self.callback = callback
        self.inbox = Queue()
        self.outbox = Queue()

    def enqueue(self, event):
        self.inbox.put(event)
        Timer(self.cooldown, self.process).start()

    def process(self):
        self.outbox.put(self.inbox.get())
        if self.inbox.empty():
            events = []
            while not self.outbox.empty():
                events.append(self.outbox.get())
            self.callback(events)


import warnings

from django.conf.urls import include, url
from django.conf import settings
from django.conf.urls.static import static

from django.contrib import admin

admin.autodiscover()

# Turns deprecation warnings into errors
warnings.simplefilter('error', DeprecationWarning)

urlpatterns = [
    # Examples:
    # url(r'^$', 'SigmaPi.views.home', name='home'),
    # url(r'^SigmaPi/', include('SigmaPi.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', admin.site.urls),
    url(r'^users/', include('UserInfo.urls')),
    url(r'^secure/', include('Secure.urls')),
    url(r'^', include('PubSite.urls')),
]

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Response:
<REPLACE_OLD> from <REPLACE_NEW> import warnings

from <REPLACE_END> <REPLACE_OLD> static

# Uncomment the next two lines to enable the admin:
from <REPLACE_NEW> static

from <REPLACE_END> <REPLACE_OLD> admin

admin.autodiscover()

urlpatterns <REPLACE_NEW> admin

admin.autodiscover()

# Turns deprecation warnings into errors
warnings.simplefilter('error', DeprecationWarning)

urlpatterns <REPLACE_END> <REPLACE_OLD> include(admin.site.urls)),
 <REPLACE_NEW> admin.site.urls),
 <REPLACE_END> <|endoftext|> import warnings

from django.conf.urls import include, url
from django.conf import settings
from django.conf.urls.static import static

from django.contrib import admin

admin.autodiscover()

# Turns deprecation warnings into errors
warnings.simplefilter('error', DeprecationWarning)

urlpatterns = [
    # Examples:
    # url(r'^$', 'SigmaPi.views.home', name='home'),
    # url(r'^SigmaPi/', include('SigmaPi.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', admin.site.urls),
    url(r'^users/', include('UserInfo.urls')),
    url(r'^secure/', include('Secure.urls')),
    url(r'^', include('PubSite.urls')),
]

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Prompt:
Fix admin URLs; turn deprecation warnings into errors

from django.conf.urls import include, url
from django.conf import settings
from django.conf.urls.static import static

# Uncomment the next two lines to enable the admin:
from django.contrib import admin

admin.autodiscover()

urlpatterns = [
    # Examples:
    # url(r'^$', 'SigmaPi.views.home', name='home'),
    # url(r'^SigmaPi/', include('SigmaPi.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    url(r'^admin/', include(admin.site.urls)),
    url(r'^users/', include('UserInfo.urls')),
    url(r'^secure/', include('Secure.urls')),
    url(r'^', include('PubSite.urls')),
]

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)


from fabric.api import execute, local, settings, task

@task
def docs():
    local('make -C docs/ html')

@task
def autodocs():
    auto(docs)

@task
def test(path=None):
    path = path or 'tests/'
    local('nosetests ' + path)

@task
def autotest(path=None):
    auto(test, path=path)

@task
def coverage(path=None):
    path = path or 'tests/'
    local(
        'nosetests --with-coverage --cover-package=mopidy '
        '--cover-branches --cover-html ' + path)

@task
def autocoverage(path=None):
    auto(coverage, path=path)

@task
def lint(path=None):
    path = path or '.'
    local('flake8 $(find %s -iname "*.py")' % path)

@task
def autolint(path=None):
    auto(lint, path=path)

def auto(task, *args, **kwargs):
    while True:
        local('clear')
        with settings(warn_only=True):
            execute(task, *args, **kwargs)
        local(
            'inotifywait -q -e create -e modify -e delete '
            '--exclude ".*\.(pyc|sw.)" -r docs/ mopidy/ tests/')

@task
def update_authors():
    # Keep authors in the order of appearance and use awk to filter out dupes
    local(
        "git log --format='- %aN <%aE>' --reverse | awk '!x[$0]++' > AUTHORS")

Response:
<INSERT> path=path)

@task
def lint(path=None):
    path = path or '.'
    local('flake8 $(find %s -iname "*.py")' % path)

@task
def autolint(path=None):
    auto(lint, <INSERT_END> <|endoftext|> from fabric.api import execute, local, settings, task

@task
def docs():
    local('make -C docs/ html')

@task
def autodocs():
    auto(docs)

@task
def test(path=None):
    path = path or 'tests/'
    local('nosetests ' + path)

@task
def autotest(path=None):
    auto(test, path=path)

@task
def coverage(path=None):
    path = path or 'tests/'
    local(
        'nosetests --with-coverage --cover-package=mopidy '
        '--cover-branches --cover-html ' + path)

@task
def autocoverage(path=None):
    auto(coverage, path=path)

@task
def lint(path=None):
    path = path or '.'
    local('flake8 $(find %s -iname "*.py")' % path)

@task
def autolint(path=None):
    auto(lint, path=path)

def auto(task, *args, **kwargs):
    while True:
        local('clear')
        with settings(warn_only=True):
            execute(task, *args, **kwargs)
        local(
            'inotifywait -q -e create -e modify -e delete '
            '--exclude ".*\.(pyc|sw.)" -r docs/ mopidy/ tests/')

@task
def update_authors():
    # Keep authors in the order of appearance and use awk to filter out dupes
    local(
        "git log --format='- %aN <%aE>' --reverse | awk '!x[$0]++' > AUTHORS")

Prompt:
fab: Add lint/autolint tasks for running flake8 on everything

from fabric.api import execute, local, settings, task

@task
def docs():
    local('make -C docs/ html')

@task
def autodocs():
    auto(docs)

@task
def test(path=None):
    path = path or 'tests/'
    local('nosetests ' + path)

@task
def autotest(path=None):
    auto(test, path=path)

@task
def coverage(path=None):
    path = path or 'tests/'
    local(
        'nosetests --with-coverage --cover-package=mopidy '
        '--cover-branches --cover-html ' + path)

@task
def autocoverage(path=None):
    auto(coverage, path=path)

def auto(task, *args, **kwargs):
    while True:
        local('clear')
        with settings(warn_only=True):
            execute(task, *args, **kwargs)
        local(
            'inotifywait -q -e create -e modify -e delete '
            '--exclude ".*\.(pyc|sw.)" -r docs/ mopidy/ tests/')

@task
def update_authors():
    # Keep authors in the order of appearance and use awk to filter out dupes
    local(
        "git log --format='- %aN <%aE>' --reverse | awk '!x[$0]++' > AUTHORS")


Add external driver and parameter file

Add external driver and parameter file

Response:
<INSERT> #=================================================
# Observation
#-------------------------------------------------
sstObsPath = '/clim_obs/obs/ocn/mo/tos/UKMETOFFICE-HadISST-v1-1/130122_HadISST_sst.nc'
tauxObsPath = '/clim_obs/obs/atm/mo/tauu/ERAINT/tauu_ERAINT_198901-200911.nc'

sstNameObs = 'sst'
tauxNameObs = 'tauu'

#=================================================
# Models
#-------------------------------------------------
modpath = '/work/cmip5/historical/atm/mo/VAR/cmip5.MOD.historical.r1i1p1.mo.atm.Amon.VAR.ver-1.latestX.xml'

modnames = ['ACCESS1-0', 'ACCESS1-3',
 <INSERT_END> <INSERT>           'BNU-ESM',
            'CMCC-CESM', 'CMCC-CM', 'CMCC-CMS',
            'CSIRO-Mk3-6-0', 'CanCM4',
            'GISS-E2-H-CC', 'GISS-E2-H', 'GISS-E2-R-CC', 'GISS-E2-R',
            'HadCM3', 'HadGEM2-AO', 'HadGEM2-CC', 'HadGEM2-ES',
            'IPSL-CM5A-LR',
            'MIROC-ESM-CHEM', 'MIROC-ESM', 'MIROC4h', 'MIROC5',
            'MPI-ESM-LR', 'MPI-ESM-MR',
            'inmcm4'
           ]
modnames = ['IPSL-CM5A-LR']

# Variables
sstName = 'ts'
tauxName= 'tauu'

#=================================================
# Output
#-------------------------------------------------
outpathdata = '.' # e.g. '/user/directory/output/nc'
outpathjsons = '.' # e.g. '/user/directory/output/json'
outnamejson = 'test.json'

#=================================================
# Output
#-------------------------------------------------
# Metrics
metrics = ['EnsoAmpl', 'EnsoMu']

# Variable name and nino box
ninoBox = 'nino3'
 <INSERT_END> <|endoftext|> #=================================================
# Observation
#-------------------------------------------------
sstObsPath = '/clim_obs/obs/ocn/mo/tos/UKMETOFFICE-HadISST-v1-1/130122_HadISST_sst.nc'
tauxObsPath = '/clim_obs/obs/atm/mo/tauu/ERAINT/tauu_ERAINT_198901-200911.nc'

sstNameObs = 'sst'
tauxNameObs = 'tauu'

#=================================================
# Models
#-------------------------------------------------
modpath = '/work/cmip5/historical/atm/mo/VAR/cmip5.MOD.historical.r1i1p1.mo.atm.Amon.VAR.ver-1.latestX.xml'

modnames = ['ACCESS1-0', 'ACCESS1-3',
            'BNU-ESM',
            'CMCC-CESM', 'CMCC-CM', 'CMCC-CMS',
            'CSIRO-Mk3-6-0', 'CanCM4',
            'GISS-E2-H-CC', 'GISS-E2-H', 'GISS-E2-R-CC', 'GISS-E2-R',
            'HadCM3', 'HadGEM2-AO', 'HadGEM2-CC', 'HadGEM2-ES',
            'IPSL-CM5A-LR',
            'MIROC-ESM-CHEM', 'MIROC-ESM', 'MIROC4h', 'MIROC5',
            'MPI-ESM-LR', 'MPI-ESM-MR',
            'inmcm4'
           ]
modnames = ['IPSL-CM5A-LR']

# Variables
sstName = 'ts'
tauxName= 'tauu'

#=================================================
# Output
#-------------------------------------------------
outpathdata = '.' # e.g. '/user/directory/output/nc'
outpathjsons = '.' # e.g. '/user/directory/output/json'
outnamejson = 'test.json'

#=================================================
# Output
#-------------------------------------------------
# Metrics
metrics = ['EnsoAmpl', 'EnsoMu']

# Variable name and nino box
ninoBox = 'nino3'

Prompt: Add external driver and parameter file


"""
This class containts some frequently-used constants
"""

class Environment:
    QA = "qa"
    STAGING = "staging"
    PRODUCTION = "production"
    MASTER = "master"
    LOCAL = "local"
    TEST = "test"

class Files:
    DOWNLOADS_FOLDER = "downloaded_files"
    ARCHIVED_DOWNLOADS_FOLDER = "archived_files"

class ValidBrowsers:
    valid_browsers = ["firefox", "ie", "edge", "safari", "chrome", "phantomjs"]

class Browser:
    FIREFOX = "firefox"
    INTERNET_EXPLORER = "ie"
    EDGE = "edge"
    SAFARI = "safari"
    GOOGLE_CHROME = "chrome"
    PHANTOM_JS = "phantomjs"

    VERSION = {
        "firefox": None,
        "ie": None,
        "edge": None,
        "safari": None,
        "chrome": None,
        "phantomjs": None
    }

    LATEST = {
        "firefox": None,
        "ie": None,
        "edge": None,
        "safari": None,
        "chrome": None,
        "phantomjs": None
    }

class State:
    NOTRUN = "NotRun"
    ERROR = "Error"
    FAILURE = "Fail"
    PASS = "Pass"
    SKIP = "Skip"
    BLOCKED = "Blocked"
    DEPRECATED = "Deprecated"

Remove "htmlunit" from browser options

Remove "htmlunit" from browser options

Response:
<REPLACE_OLD> "phantomjs"
    HTML_UNIT = "htmlunit"

 <REPLACE_NEW> "phantomjs"

 <REPLACE_END> <DELETE> None,
        "htmlunit": <DELETE_END> <DELETE> None,
        "htmlunit": <DELETE_END> <|endoftext|> """
This class containts some frequently-used constants
"""

class Environment:
    QA = "qa"
    STAGING = "staging"
    PRODUCTION = "production"
    MASTER = "master"
    LOCAL = "local"
    TEST = "test"

class Files:
    DOWNLOADS_FOLDER = "downloaded_files"
    ARCHIVED_DOWNLOADS_FOLDER = "archived_files"

class ValidBrowsers:
    valid_browsers = ["firefox", "ie", "edge", "safari", "chrome", "phantomjs"]

class Browser:
    FIREFOX = "firefox"
    INTERNET_EXPLORER = "ie"
    EDGE = "edge"
    SAFARI = "safari"
    GOOGLE_CHROME = "chrome"
    PHANTOM_JS = "phantomjs"

    VERSION = {
        "firefox": None,
        "ie": None,
        "edge": None,
        "safari": None,
        "chrome": None,
        "phantomjs": None
    }

    LATEST = {
        "firefox": None,
        "ie": None,
        "edge": None,
        "safari": None,
        "chrome": None,
        "phantomjs": None
    }

class State:
    NOTRUN = "NotRun"
    ERROR = "Error"
    FAILURE = "Fail"
    PASS = "Pass"
    SKIP = "Skip"
    BLOCKED = "Blocked"
    DEPRECATED = "Deprecated"

Prompt:
Remove "htmlunit" from browser options

"""
This class containts some frequently-used constants
"""

class Environment:
    QA = "qa"
    STAGING = "staging"
    PRODUCTION = "production"
    MASTER = "master"
    LOCAL = "local"
    TEST = "test"

class Files:
    DOWNLOADS_FOLDER = "downloaded_files"
    ARCHIVED_DOWNLOADS_FOLDER = "archived_files"

class ValidBrowsers:
    valid_browsers = ["firefox", "ie", "edge", "safari", "chrome", "phantomjs"]

class Browser:
    FIREFOX = "firefox"
    INTERNET_EXPLORER = "ie"
    EDGE = "edge"
    SAFARI = "safari"
    GOOGLE_CHROME = "chrome"
    PHANTOM_JS = "phantomjs"
    HTML_UNIT = "htmlunit"

    VERSION = {
        "firefox": None,
        "ie": None,
        "edge": None,
        "safari": None,
        "chrome": None,
        "phantomjs": None,
        "htmlunit": None
    }

    LATEST = {
        "firefox": None,
        "ie": None,
        "edge": None,
        "safari": None,
        "chrome": None,
        "phantomjs": None,
        "htmlunit": None
    }

class State:
    NOTRUN = "NotRun"
    ERROR = "Error"
    FAILURE = "Fail"
    PASS = "Pass"
    SKIP = "Skip"
    BLOCKED = "Blocked"
    DEPRECATED = "Deprecated"


# Implement a function that takes two strings, s and x, as arguments and finds the first occurrence of the string x in s. The function should return an integer indicating the index in s of the first occurrence of x. If there are no occurrences of x in s, return -1

def find_substring(string, substr):
	string_len = len(string)
	substr_len = len(substr)
	i = 0

	if substr_len >= 1:
		i = 0
		while i < string_len:
			if string[i] == substr[j]:
				if j == substr_len:
					return i - substr_len
					j += 1
				else:
					j = 0
		i += 1

	return -1

Return -1 if no substring is found

Return -1 if no substring is found

Response:
<REPLACE_OLD> 1
 <REPLACE_NEW> 1

	return -1
 <REPLACE_END> <|endoftext|> # Implement a function that takes two strings, s and x, as arguments and finds the first occurrence of the string x in s. The function should return an integer indicating the index in s of the first occurrence of x. If there are no occurrences of x in s, return -1

def find_substring(string, substr):
	string_len = len(string)
	substr_len = len(substr)
	i = 0

	if substr_len >= 1:
		i = 0
		while i < string_len:
			if string[i] == substr[j]:
				if j == substr_len:
					return i - substr_len
					j += 1
				else:
					j = 0
		i += 1

	return -1

Prompt:
Return -1 if no substring is found

# Implement a function that takes two strings, s and x, as arguments and finds the first occurrence of the string x in s. The function should return an integer indicating the index in s of the first occurrence of x. If there are no occurrences of x in s, return -1

def find_substring(string, substr):
	string_len = len(string)
	substr_len = len(substr)
	i = 0

	if substr_len >= 1:
		i = 0
		while i < string_len:
			if string[i] == substr[j]:
				if j == substr_len:
					return i - substr_len
					j += 1
				else:
					j = 0
		i += 1


import numpy as np
import pandas

def main():
	data = pandas.read_csv('sarcasm_v2.csv').as_matrix()
	# print(data.shape)
	data[:, 0] = np.array([find_category(x) for x in data[:, 0]])
	data[:, 1] = np.array([sarcasm(x) for x in data[:, 1]])
	# print(data[0,1]) # should be 1 for sarcasm

def find_category(category):
	return {
        'GEN': 0, # general
        'HYP': 1, # hyperbole
		'RQ': 2 # rhetorical question
    }[category]

def sarcasm(sarcasm_value):
	return {
		'sarc': 1, # true for sarcasm
		'notsarc': 0 # false for sarcasm
	}[sarcasm_value]

def get_data_index(ID):
	'''find the index of the data point. Corresponds to 1234 in GEN_sarc_1234 under ID in data.
	'''
	# TODO: given a string as shown in the comment, extract the number in it, possibly with regex.

if __name__ == '__main__':
	main()

Add TODO comment for get_data_index

Add TODO comment for get_data_index

Response:
<REPLACE_OLD> TODO

if <REPLACE_NEW> TODO: given a string as shown in the comment, extract the number in it, possibly with regex.

if <REPLACE_END> <|endoftext|> import numpy as np
import pandas

def main():
	data = pandas.read_csv('sarcasm_v2.csv').as_matrix()
	# print(data.shape)
	data[:, 0] = np.array([find_category(x) for x in data[:, 0]])
	data[:, 1] = np.array([sarcasm(x) for x in data[:, 1]])
	# print(data[0,1]) # should be 1 for sarcasm

def find_category(category):
	return {
        'GEN': 0, # general
        'HYP': 1, # hyperbole
		'RQ': 2 # rhetorical question
    }[category]

def sarcasm(sarcasm_value):
	return {
		'sarc': 1, # true for sarcasm
		'notsarc': 0 # false for sarcasm
	}[sarcasm_value]

def get_data_index(ID):
	'''find the index of the data point. Corresponds to 1234 in GEN_sarc_1234 under ID in data.
	'''
	# TODO: given a string as shown in the comment, extract the number in it, possibly with regex.

if __name__ == '__main__':
	main()

Prompt:
Add TODO comment for get_data_index

import numpy as np
import pandas

def main():
	data = pandas.read_csv('sarcasm_v2.csv').as_matrix()
	# print(data.shape)
	data[:, 0] = np.array([find_category(x) for x in data[:, 0]])
	data[:, 1] = np.array([sarcasm(x) for x in data[:, 1]])
	# print(data[0,1]) # should be 1 for sarcasm

def find_category(category):
	return {
        'GEN': 0, # general
        'HYP': 1, # hyperbole
		'RQ': 2 # rhetorical question
    }[category]

def sarcasm(sarcasm_value):
	return {
		'sarc': 1, # true for sarcasm
		'notsarc': 0 # false for sarcasm
	}[sarcasm_value]

def get_data_index(ID):
	'''find the index of the data point. Corresponds to 1234 in GEN_sarc_1234 under ID in data.
	'''
	# TODO

if __name__ == '__main__':
	main()


# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

from telemetry.internal.backends.chrome_inspector import inspector_websocket
from telemetry.core import exceptions

class InspectorServiceWorker(object):
  def __init__(self, inspector_socket, timeout):
    self._websocket = inspector_socket
    self._websocket.RegisterDomain('ServiceWorker', self._OnNotification)
    # ServiceWorker.enable RPC must be called before calling any other methods
    # in ServiceWorker domain.
    res = self._websocket.SyncRequest(
        {'method': 'ServiceWorker.enable'}, timeout)
    if 'error' in res:
      raise exceptions.StoryActionError(res['error']['message'])

  def _OnNotification(self, msg):
    # TODO: track service worker events
    # (https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker/)
    pass

  def StopAllWorkers(self, timeout):
    res = self._websocket.SyncRequest(
        {'method': 'ServiceWorker.stopAllWorkers'}, timeout)
    if 'error' in res:
      code = res['error']['code']
      if code == inspector_websocket.InspectorWebsocket.METHOD_NOT_FOUND_CODE:
        raise NotImplementedError(
            'DevTools method ServiceWorker.stopAllWorkers is not supported by '
            'this browser.')
      raise exceptions.StoryActionError(res['error']['message'])

Response:
<INSERT> telemetry.internal.backends.chrome_inspector import inspector_websocket
from <INSERT_END> <REPLACE_OLD> exceptions

class <REPLACE_NEW> exceptions

class <REPLACE_END> <REPLACE_OLD> inspector_websocket, <REPLACE_NEW> inspector_socket, <REPLACE_END> <REPLACE_OLD> inspector_websocket
 <REPLACE_NEW> inspector_socket
 <REPLACE_END> <INSERT> code = res['error']['code']
      if code == inspector_websocket.InspectorWebsocket.METHOD_NOT_FOUND_CODE:
        raise NotImplementedError(
            'DevTools method ServiceWorker.stopAllWorkers is not supported by '
            'this browser.')
      <INSERT_END> <|endoftext|> # Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

from telemetry.internal.backends.chrome_inspector import inspector_websocket
from telemetry.core import exceptions

class InspectorServiceWorker(object):
  def __init__(self, inspector_socket, timeout):
    self._websocket = inspector_socket
    self._websocket.RegisterDomain('ServiceWorker', self._OnNotification)
    # ServiceWorker.enable RPC must be called before calling any other methods
    # in ServiceWorker domain.
    res = self._websocket.SyncRequest(
        {'method': 'ServiceWorker.enable'}, timeout)
    if 'error' in res:
      raise exceptions.StoryActionError(res['error']['message'])

  def _OnNotification(self, msg):
    # TODO: track service worker events
    # (https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker/)
    pass

  def StopAllWorkers(self, timeout):
    res = self._websocket.SyncRequest(
        {'method': 'ServiceWorker.stopAllWorkers'}, timeout)
    if 'error' in res:
      code = res['error']['code']
      if code == inspector_websocket.InspectorWebsocket.METHOD_NOT_FOUND_CODE:
        raise NotImplementedError(
            'DevTools method ServiceWorker.stopAllWorkers is not supported by '
            'this browser.')
      raise exceptions.StoryActionError(res['error']['message'])

Prompt:
Handle error code METHOD_NOT_FOUND_CODE in InspectorServiceWorker.StopAllWorkers()

DevTools method ServiceWorker.stopAllWorkers is supported from M63, so
calling this can return METHOD_NOT_FOUND_CODE error in previous browser.
This CL make InspectorServiceWorker.StopAllWorkers() handle this error.
If it receives this error, it raises NotImplementedError.

This is implemented in the same way with memory_backend.py does.
https://cs.chromium.org/chromium/src/third_party/catapult/telemetry/telemetry/internal/backends/chrome_inspector/memory_backend.py?type=cs&q=warn+file:%5Esrc/third_party/catapult/telemetry/telemetry/internal/backends/chrome_inspector/+package:%5Echromium$&l=84

BUG=chromium:736697

Review-Url: https://chromiumcodereview.appspot.com/3013263002

# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

from telemetry.core import exceptions

class InspectorServiceWorker(object):
  def __init__(self, inspector_websocket, timeout):
    self._websocket = inspector_websocket
    self._websocket.RegisterDomain('ServiceWorker', self._OnNotification)
    # ServiceWorker.enable RPC must be called before calling any other methods
    # in ServiceWorker domain.
    res = self._websocket.SyncRequest(
        {'method': 'ServiceWorker.enable'}, timeout)
    if 'error' in res:
      raise exceptions.StoryActionError(res['error']['message'])

  def _OnNotification(self, msg):
    # TODO: track service worker events
    # (https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker/)
    pass

  def StopAllWorkers(self, timeout):
    res = self._websocket.SyncRequest(
        {'method': 'ServiceWorker.stopAllWorkers'}, timeout)
    if 'error' in res:
      raise exceptions.StoryActionError(res['error']['message'])


#!/usr/bin/env python
from setuptools import setup, find_packages

setup(name='bettercache',
    version='0.5.3',
    description = "A suite of better cache tools for Django.",
    license = "MIT",
    author='Calvin Spealman',
    author_email='ironfroggy@gmail.com',
    url='http://github.com/ironfroggy/django-better-cache',
    packages = find_packages(),
    install_requires = [
        'celery >= 2.4.2',
        'httplib2 >= 0.6.0',
    ],
)

Response:
<REPLACE_OLD> find_packages(),
)
 <REPLACE_NEW> find_packages(),
    install_requires = [
        'celery >= 2.4.2',
        'httplib2 >= 0.6.0',
    ],
)
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
from setuptools import setup, find_packages

setup(name='bettercache',
    version='0.5.3',
    description = "A suite of better cache tools for Django.",
    license = "MIT",
    author='Calvin Spealman',
    author_email='ironfroggy@gmail.com',
    url='http://github.com/ironfroggy/django-better-cache',
    packages = find_packages(),
    install_requires = [
        'celery >= 2.4.2',
        'httplib2 >= 0.6.0',
    ],
)

Prompt:
Add new requirements from CMG middleware

#!/usr/bin/env python
from setuptools import setup, find_packages

setup(name='bettercache',
    version='0.5.3',
    description = "A suite of better cache tools for Django.",
    license = "MIT",
    author='Calvin Spealman',
    author_email='ironfroggy@gmail.com',
    url='http://github.com/ironfroggy/django-better-cache',
    packages = find_packages(),
)


# -*- coding: utf-8 -*-
"""sda

.. codeauthor:: John Lane <jlane@fanthreesixty.com>

"""

from sda import locators
from sda import mixins
from sda import structures
from sda.element import Element
from sda.page import Page
from sda.site import Site

__author__ = 'jlane'
__email__ = 'jlane@fanthreesixty.com'
__license__ = "MIT"
__version__ = '0.9.1'

__all__ = ['locators', 'shortcuts', 'structures', 'Element', 'Page', 'Site']

Response:
<DELETE> element
from sda import <DELETE_END> <REPLACE_OLD> page
from sda <REPLACE_NEW> structures
from sda.element <REPLACE_END> <REPLACE_OLD> site
from sda <REPLACE_NEW> Element
from sda.page <REPLACE_END> <REPLACE_OLD> structures

__author__ <REPLACE_NEW> Page
from sda.site import Site

__author__ <REPLACE_END> <REPLACE_OLD> ['element', 'locators', 'page', <REPLACE_NEW> ['locators', <REPLACE_END> <REPLACE_OLD> 'site', 'structures']
 <REPLACE_NEW> 'structures', 'Element', 'Page', 'Site']
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
"""sda

.. codeauthor:: John Lane <jlane@fanthreesixty.com>

"""

from sda import locators
from sda import mixins
from sda import structures
from sda.element import Element
from sda.page import Page
from sda.site import Site

__author__ = 'jlane'
__email__ = 'jlane@fanthreesixty.com'
__license__ = "MIT"
__version__ = '0.9.1'

__all__ = ['locators', 'shortcuts', 'structures', 'Element', 'Page', 'Site']

Prompt:
Streamline imports for Element, Page and Site

# -*- coding: utf-8 -*-
"""sda

.. codeauthor:: John Lane <jlane@fanthreesixty.com>

"""

from sda import element
from sda import locators
from sda import mixins
from sda import page
from sda import site
from sda import structures

__author__ = 'jlane'
__email__ = 'jlane@fanthreesixty.com'
__license__ = "MIT"
__version__ = '0.9.1'

__all__ = ['element', 'locators', 'page', 'shortcuts', 'site', 'structures']


try:
    from setuptools import setup, find_packages
except ImportError:
    from ez_setup import use_setuptools
    use_setuptools()
    from setuptools import setup, find_packages

setup(
    name='debexpo',
    version="",
    #description='',
    #author='',
    #author_email='',
    #url='',
    install_requires=[
        "Pylons>=1.0",
        "SQLAlchemy>=0.6",
        "Webhelpers>=0.6.1",
        "Babel>=0.9.6",
        "ZSI",
        "python-debian>=0.1.16",
        "soaplib==0.8.1"],
    packages=find_packages(exclude=['ez_setup']),
    include_package_data=True,
    test_suite='nose.collector',
    package_data={'debexpo': ['i18n/*/LC_MESSAGES/*.mo']},
    message_extractors = {'debexpo': [
            ('**.py', 'python', None),
            ('templates/**.mako', 'mako', None),
            ('public/**', 'ignore', None)]},
    entry_points="""
    [paste.app_factory]
    main = debexpo.config.middleware:make_app

    [paste.app_install]
    main = pylons.util:PylonsInstaller

    [console_scripts]
    debexpo-importer = debexpo.scripts.debexpo_importer:main
    debexpo-user-importer = debexpo.scripts.user_importer:main
    """,
)

Response:
<REPLACE_OLD> "python-debian==0.1.16",
 <REPLACE_NEW> "python-debian>=0.1.16",
 <REPLACE_END> <|endoftext|> try:
    from setuptools import setup, find_packages
except ImportError:
    from ez_setup import use_setuptools
    use_setuptools()
    from setuptools import setup, find_packages

setup(
    name='debexpo',
    version="",
    #description='',
    #author='',
    #author_email='',
    #url='',
    install_requires=[
        "Pylons>=1.0",
        "SQLAlchemy>=0.6",
        "Webhelpers>=0.6.1",
        "Babel>=0.9.6",
        "ZSI",
        "python-debian>=0.1.16",
        "soaplib==0.8.1"],
    packages=find_packages(exclude=['ez_setup']),
    include_package_data=True,
    test_suite='nose.collector',
    package_data={'debexpo': ['i18n/*/LC_MESSAGES/*.mo']},
    message_extractors = {'debexpo': [
            ('**.py', 'python', None),
            ('templates/**.mako', 'mako', None),
            ('public/**', 'ignore', None)]},
    entry_points="""
    [paste.app_factory]
    main = debexpo.config.middleware:make_app

    [paste.app_install]
    main = pylons.util:PylonsInstaller

    [console_scripts]
    debexpo-importer = debexpo.scripts.debexpo_importer:main
    debexpo-user-importer = debexpo.scripts.user_importer:main
    """,
)

Prompt:
Make library dependencies python-debian a bit more sane

try:
    from setuptools import setup, find_packages
except ImportError:
    from ez_setup import use_setuptools
    use_setuptools()
    from setuptools import setup, find_packages

setup(
    name='debexpo',
    version="",
    #description='',
    #author='',
    #author_email='',
    #url='',
    install_requires=[
        "Pylons>=1.0",
        "SQLAlchemy>=0.6",
        "Webhelpers>=0.6.1",
        "Babel>=0.9.6",
        "ZSI",
        "python-debian==0.1.16",
        "soaplib==0.8.1"],
    packages=find_packages(exclude=['ez_setup']),
    include_package_data=True,
    test_suite='nose.collector',
    package_data={'debexpo': ['i18n/*/LC_MESSAGES/*.mo']},
    message_extractors = {'debexpo': [
            ('**.py', 'python', None),
            ('templates/**.mako', 'mako', None),
            ('public/**', 'ignore', None)]},
    entry_points="""
    [paste.app_factory]
    main = debexpo.config.middleware:make_app

    [paste.app_install]
    main = pylons.util:PylonsInstaller

    [console_scripts]
    debexpo-importer = debexpo.scripts.debexpo_importer:main
    debexpo-user-importer = debexpo.scripts.user_importer:main
    """,
)


# -*- coding: utf-8 -*-
# from __future__ import unicode_literals
from django.conf.urls import url
from darchan import views

urlpatterns = [
    url(r'^view_matrix/$',
        views.v_view_last_matrix, name='view_last_matrix'),
    url(r'^view_matrix/(?P<builder_id>\d+)/(?P<depth>\d+)/$',
        views.v_view_matrix, name='view_matrix'),
    url(r'^generate_matrix/$',
        views.v_generate_matrix, name='generate_matrix'),
    url(r'^download_csv/(?P<builder_id>\d+)/(?P<depth>\d+)/$',
        views.v_download_csv, name='download_csv'),
]

Update support to Django 1.9

Update support to Django 1.9

Response:
<REPLACE_OLD> -*-
from <REPLACE_NEW> -*-
# from <REPLACE_END> <REPLACE_OLD> patterns, url

urlpatterns <REPLACE_NEW> url
from darchan import views

urlpatterns <REPLACE_END> <REPLACE_OLD> patterns(
 <REPLACE_NEW> [
 <REPLACE_END> <REPLACE_OLD> 'darchan.views',
    url(r'^view_matrix/$', 'v_view_last_matrix', name='view_last_matrix'),
    url(r'^view_matrix/(?P<builder_id>\d+)/(?P<depth>\d+)/$', 'v_view_matrix',
 <REPLACE_NEW> url(r'^view_matrix/$',
 <REPLACE_END> <INSERT> views.v_view_last_matrix, name='view_last_matrix'),
    url(r'^view_matrix/(?P<builder_id>\d+)/(?P<depth>\d+)/$',
        views.v_view_matrix, <INSERT_END> <REPLACE_OLD> url(r'^generate_matrix/$', 'v_generate_matrix', <REPLACE_NEW> url(r'^generate_matrix/$',
        views.v_generate_matrix, <REPLACE_END> <REPLACE_OLD> 'v_download_csv', name='download_csv'),
)
 <REPLACE_NEW> views.v_download_csv, name='download_csv'),
]
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
# from __future__ import unicode_literals
from django.conf.urls import url
from darchan import views

urlpatterns = [
    url(r'^view_matrix/$',
        views.v_view_last_matrix, name='view_last_matrix'),
    url(r'^view_matrix/(?P<builder_id>\d+)/(?P<depth>\d+)/$',
        views.v_view_matrix, name='view_matrix'),
    url(r'^generate_matrix/$',
        views.v_generate_matrix, name='generate_matrix'),
    url(r'^download_csv/(?P<builder_id>\d+)/(?P<depth>\d+)/$',
        views.v_download_csv, name='download_csv'),
]

Prompt:
Update support to Django 1.9

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import patterns, url

urlpatterns = patterns(
    'darchan.views',
    url(r'^view_matrix/$', 'v_view_last_matrix', name='view_last_matrix'),
    url(r'^view_matrix/(?P<builder_id>\d+)/(?P<depth>\d+)/$', 'v_view_matrix',
        name='view_matrix'),
    url(r'^generate_matrix/$', 'v_generate_matrix', name='generate_matrix'),
    url(r'^download_csv/(?P<builder_id>\d+)/(?P<depth>\d+)/$',
        'v_download_csv', name='download_csv'),
)


# -*- coding: utf-8 -*-
#
# Copyright (C) 2013 Alexander Shorin
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#

class DecodeError(ValueError):
    """UBJSON data decoding error."""

class MarkerError(DecodeError):
    """Raises if unknown or invalid marker was found in decoded data stream."""

class EarlyEndOfStreamError(DecodeError):
    """Raises when data stream unexpectedly ends."""

class EncodeError(TypeError):
    """Python object encoding error."""

Add missed exception module. Ooops.

Add missed exception module. Ooops.

Response:
<INSERT> # -*- coding: utf-8 -*-
#
# Copyright (C) 2013 Alexander Shorin
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#

class DecodeError(ValueError):
 <INSERT_END> <INSERT>   """UBJSON data decoding error."""

class MarkerError(DecodeError):
    """Raises if unknown or invalid marker was found in decoded data stream."""

class EarlyEndOfStreamError(DecodeError):
    """Raises when data stream unexpectedly ends."""

class EncodeError(TypeError):
    """Python object encoding error."""
 <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
#
# Copyright (C) 2013 Alexander Shorin
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#

class DecodeError(ValueError):
    """UBJSON data decoding error."""

class MarkerError(DecodeError):
    """Raises if unknown or invalid marker was found in decoded data stream."""

class EarlyEndOfStreamError(DecodeError):
    """Raises when data stream unexpectedly ends."""

class EncodeError(TypeError):
    """Python object encoding error."""

Prompt: Add missed exception module. Ooops.


#!/usr/bin/env python

"""Setup script for PythonTemplateDemo."""

import setuptools

from demo import __project__, __version__

try:
    README = open("README.rst").read()
    CHANGELOG = open("CHANGELOG.rst").read()
except IOError:
    LONG_DESCRIPTION = "Coming soon..."
else:
    LONG_DESCRIPTION = README + '\n' + CHANGELOG

setuptools.setup(
    name=__project__,
    version=__version__,

    description="A sample project templated from jacebrowning/template-python.",
    url='https://github.com/jacebrowning/template-python-demo',
    author='Jace Browning',
    author_email='jacebrowning@gmail.com',

    packages=setuptools.find_packages(),

    entry_points={'console_scripts': []},

    long_description=LONG_DESCRIPTION,
    license='MIT',
    classifiers=[
        # TODO: update this list to match your application: https://pypi.python.org/pypi?%3Aaction=list_classifiers
        'Development Status :: 1 - Planning',
        'Natural Language :: English',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],

    install_requires=open("requirements.txt").readlines(),
)

Deploy Travis CI build 715 to GitHub

Deploy Travis CI build 715 to GitHub

Response:
<REPLACE_OLD> DESCRIPTION = "<placeholder>"
else:
    DESCRIPTION <REPLACE_NEW> LONG_DESCRIPTION = "Coming soon..."
else:
    LONG_DESCRIPTION <REPLACE_END> <REPLACE_OLD> long_description=(DESCRIPTION),
 <REPLACE_NEW> long_description=LONG_DESCRIPTION,
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

"""Setup script for PythonTemplateDemo."""

import setuptools

from demo import __project__, __version__

try:
    README = open("README.rst").read()
    CHANGELOG = open("CHANGELOG.rst").read()
except IOError:
    LONG_DESCRIPTION = "Coming soon..."
else:
    LONG_DESCRIPTION = README + '\n' + CHANGELOG

setuptools.setup(
    name=__project__,
    version=__version__,

    description="A sample project templated from jacebrowning/template-python.",
    url='https://github.com/jacebrowning/template-python-demo',
    author='Jace Browning',
    author_email='jacebrowning@gmail.com',

    packages=setuptools.find_packages(),

    entry_points={'console_scripts': []},

    long_description=LONG_DESCRIPTION,
    license='MIT',
    classifiers=[
        # TODO: update this list to match your application: https://pypi.python.org/pypi?%3Aaction=list_classifiers
        'Development Status :: 1 - Planning',
        'Natural Language :: English',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],

    install_requires=open("requirements.txt").readlines(),
)

Prompt:
Deploy Travis CI build 715 to GitHub

#!/usr/bin/env python

"""Setup script for PythonTemplateDemo."""

import setuptools

from demo import __project__, __version__

try:
    README = open("README.rst").read()
    CHANGELOG = open("CHANGELOG.rst").read()
except IOError:
    DESCRIPTION = "<placeholder>"
else:
    DESCRIPTION = README + '\n' + CHANGELOG

setuptools.setup(
    name=__project__,
    version=__version__,

    description="A sample project templated from jacebrowning/template-python.",
    url='https://github.com/jacebrowning/template-python-demo',
    author='Jace Browning',
    author_email='jacebrowning@gmail.com',

    packages=setuptools.find_packages(),

    entry_points={'console_scripts': []},

    long_description=(DESCRIPTION),
    license='MIT',
    classifiers=[
        # TODO: update this list to match your application: https://pypi.python.org/pypi?%3Aaction=list_classifiers
        'Development Status :: 1 - Planning',
        'Natural Language :: English',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],

    install_requires=open("requirements.txt").readlines(),
)


__version_info__ = (0, 5, 0, None)

# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join(str(i) for i in __version_info__[:-1])
if __version_info__[-1] is not None:
    __version__ += ('-%s' % (__version_info__[-1],))

Update version number for release

Update version number for release

Response:
<REPLACE_OLD> 4, <REPLACE_NEW> 5, <REPLACE_END> <|endoftext|> __version_info__ = (0, 5, 0, None)

# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join(str(i) for i in __version_info__[:-1])
if __version_info__[-1] is not None:
    __version__ += ('-%s' % (__version_info__[-1],))

Prompt:
Update version number for release

__version_info__ = (0, 4, 0, None)

# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join(str(i) for i in __version_info__[:-1])
if __version_info__[-1] is not None:
    __version__ += ('-%s' % (__version_info__[-1],))


from .compiler import ParseResult

from .expressions import (
    Alt,
    And,
    Any,
    AnyOf,
    Backtrack,
    Bind,
    End,
    Expect,
    Fail,
    ForwardRef,
    Left,
    List,
    Literal,
    Not,
    Opt,
    Or,
    Require,
    Return,
    Right,
    Some,
    Start,
    Struct,
    Term,
    Transform,
    Where,
)

from .interpreter import (
    ParseError,
    parse,
    parse_prefix,
    tokenize,
    tokenize_and_parse,
)

from .precedence import (
    InfixLeft,
    InfixRight,
    LeftAssoc,
    Operation,
    OperatorPrecedence,
    Postfix,
    Prefix,
    ReduceLeft,
    ReduceRight,
    RightAssoc,
)

from .tokens import (
    AnyChar,
    AnyString,
    Content,
    Pattern,
    Regex,
    Skip,
    Token,
    TokenSyntax,
    Verbose,
)

Add "AnyOf" to public API.

Add "AnyOf" to public API.

Response:
<INSERT> AnyOf,
    <INSERT_END> <|endoftext|> from .compiler import ParseResult

from .expressions import (
    Alt,
    And,
    Any,
    AnyOf,
    Backtrack,
    Bind,
    End,
    Expect,
    Fail,
    ForwardRef,
    Left,
    List,
    Literal,
    Not,
    Opt,
    Or,
    Require,
    Return,
    Right,
    Some,
    Start,
    Struct,
    Term,
    Transform,
    Where,
)

from .interpreter import (
    ParseError,
    parse,
    parse_prefix,
    tokenize,
    tokenize_and_parse,
)

from .precedence import (
    InfixLeft,
    InfixRight,
    LeftAssoc,
    Operation,
    OperatorPrecedence,
    Postfix,
    Prefix,
    ReduceLeft,
    ReduceRight,
    RightAssoc,
)

from .tokens import (
    AnyChar,
    AnyString,
    Content,
    Pattern,
    Regex,
    Skip,
    Token,
    TokenSyntax,
    Verbose,
)

Prompt:
Add "AnyOf" to public API.

from .compiler import ParseResult

from .expressions import (
    Alt,
    And,
    Any,
    Backtrack,
    Bind,
    End,
    Expect,
    Fail,
    ForwardRef,
    Left,
    List,
    Literal,
    Not,
    Opt,
    Or,
    Require,
    Return,
    Right,
    Some,
    Start,
    Struct,
    Term,
    Transform,
    Where,
)

from .interpreter import (
    ParseError,
    parse,
    parse_prefix,
    tokenize,
    tokenize_and_parse,
)

from .precedence import (
    InfixLeft,
    InfixRight,
    LeftAssoc,
    Operation,
    OperatorPrecedence,
    Postfix,
    Prefix,
    ReduceLeft,
    ReduceRight,
    RightAssoc,
)

from .tokens import (
    AnyChar,
    AnyString,
    Content,
    Pattern,
    Regex,
    Skip,
    Token,
    TokenSyntax,
    Verbose,
)


"""WYMeditor for Django-blog-zinnia"""
__version__ = '1.0'
__license__ = 'BSD License'

__author__ = 'Fantomas42'
__email__ = 'fantomas42@gmail.com'

__url__ = 'https://github.com/django-blog-zinnia/zinnia-wysiwyg-wymeditor'

Create zinnia_wymeditor module with his metadatas

Response:
<REPLACE_OLD>  <REPLACE_NEW> """WYMeditor for Django-blog-zinnia"""
__version__ = '1.0'
__license__ = 'BSD License'

__author__ = 'Fantomas42'
__email__ = 'fantomas42@gmail.com'

__url__ = 'https://github.com/django-blog-zinnia/zinnia-wysiwyg-wymeditor'
 <REPLACE_END> <|endoftext|> """WYMeditor for Django-blog-zinnia"""
__version__ = '1.0'
__license__ = 'BSD License'

__author__ = 'Fantomas42'
__email__ = 'fantomas42@gmail.com'

__url__ = 'https://github.com/django-blog-zinnia/zinnia-wysiwyg-wymeditor'

Prompt: Create zinnia_wymeditor module with his metadatas


import os
import sys

# Main project directory
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
STATIC_BASE_DIR = os.path.join(BASE_DIR, '../webroot')

# Static file dirs
STATIC_ROOT = os.path.join(STATIC_BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(STATIC_BASE_DIR, 'media')

# Static file URLs
STATIC_URL = '/static/'
MEDIA_URL = '/media/'

# django-pipeline settings

STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage'
if 'test' in sys.argv:
    STATICFILES_STORAGE = 'pipeline.storage.NonPackagingPipelineStorage'

STATICFILES_FINDERS = (
    'pipeline.finders.AppDirectoriesFinder',
    'pipeline.finders.PipelineFinder',
)
PIPELINE_COMPILERS = (
    'pipeline.compilers.stylus.StylusCompiler',
)

# Stylus configuration
PIPELINE_STYLUS_ARGUMENTS = ' '.join([
    '--include {path}/common/static/styl',  # Expose common styl lib dir
    '--use kouto-swiss',
]).format(path=BASE_DIR)

# Packaging specs for CSS
PIPELINE_CSS = {
    'app': {
        'source_filenames': [
            # ...
        ],
        'output_filename': 'css/app.css',
    }
}

# Packaging specs for JavaScript
PIPELINE_JS = {
}

Response:
<DELETE> Disable django-pipeline when in test mode
PIPELINE_ENABLED = 'test' not in sys.argv

# <DELETE_END> <REPLACE_OLD> settings
STATICFILES_STORAGE <REPLACE_NEW> settings

STATICFILES_STORAGE <REPLACE_END> <REPLACE_OLD> 'pipeline.storage.PipelineCachedStorage'
STATICFILES_FINDERS <REPLACE_NEW> 'pipeline.storage.PipelineCachedStorage'
if 'test' in sys.argv:
    STATICFILES_STORAGE = 'pipeline.storage.NonPackagingPipelineStorage'

STATICFILES_FINDERS <REPLACE_END> <|endoftext|> import os
import sys

# Main project directory
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
STATIC_BASE_DIR = os.path.join(BASE_DIR, '../webroot')

# Static file dirs
STATIC_ROOT = os.path.join(STATIC_BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(STATIC_BASE_DIR, 'media')

# Static file URLs
STATIC_URL = '/static/'
MEDIA_URL = '/media/'

# django-pipeline settings

STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage'
if 'test' in sys.argv:
    STATICFILES_STORAGE = 'pipeline.storage.NonPackagingPipelineStorage'

STATICFILES_FINDERS = (
    'pipeline.finders.AppDirectoriesFinder',
    'pipeline.finders.PipelineFinder',
)
PIPELINE_COMPILERS = (
    'pipeline.compilers.stylus.StylusCompiler',
)

# Stylus configuration
PIPELINE_STYLUS_ARGUMENTS = ' '.join([
    '--include {path}/common/static/styl',  # Expose common styl lib dir
    '--use kouto-swiss',
]).format(path=BASE_DIR)

# Packaging specs for CSS
PIPELINE_CSS = {
    'app': {
        'source_filenames': [
            # ...
        ],
        'output_filename': 'css/app.css',
    }
}

# Packaging specs for JavaScript
PIPELINE_JS = {
}

Prompt:
fix(set): Fix django-pipeline configuration for development/test

import os
import sys

# Disable django-pipeline when in test mode
PIPELINE_ENABLED = 'test' not in sys.argv

# Main project directory
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
STATIC_BASE_DIR = os.path.join(BASE_DIR, '../webroot')

# Static file dirs
STATIC_ROOT = os.path.join(STATIC_BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(STATIC_BASE_DIR, 'media')

# Static file URLs
STATIC_URL = '/static/'
MEDIA_URL = '/media/'

# django-pipeline settings
STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage'
STATICFILES_FINDERS = (
    'pipeline.finders.AppDirectoriesFinder',
    'pipeline.finders.PipelineFinder',
)
PIPELINE_COMPILERS = (
    'pipeline.compilers.stylus.StylusCompiler',
)

# Stylus configuration
PIPELINE_STYLUS_ARGUMENTS = ' '.join([
    '--include {path}/common/static/styl',  # Expose common styl lib dir
    '--use kouto-swiss',
]).format(path=BASE_DIR)

# Packaging specs for CSS
PIPELINE_CSS = {
    'app': {
        'source_filenames': [
            # ...
        ],
        'output_filename': 'css/app.css',
    }
}

# Packaging specs for JavaScript
PIPELINE_JS = {
}


"""
RequestContext stores state relevant to the current request, as well as
keeping track of the plugin execution order and providing a simple method
`advance` for calling the next plugin in the chain.
"""
import collections

class Container(collections.defaultdict):
    DEFAULT_FACTORY = lambda: None

    def __init__(self):
        super().__init__(self, Container.DEFAULT_FACTORY)

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

    def __setattr__(self, name, value):
        self[name] = value

class RequestContext(object):
    def __init__(self, service, operation):
        self.service = service
        self.operation = operation

    def execute(self):
        self.service.continue_execution(self)

Add building blocks Container, Context

Add building blocks Container, Context

These will be used for request/response dicts, as well as
containers for plugins to pass functions and values to the
operation function or other plugins.

Response:
<INSERT> """
RequestContext stores state relevant to the current request, as well as
keeping track of the plugin execution order and providing a simple method
`advance` for calling the next plugin in the chain.
"""
import collections

class Container(collections.defaultdict):
 <INSERT_END> <INSERT>   DEFAULT_FACTORY = lambda: None

    def __init__(self):
        super().__init__(self, Container.DEFAULT_FACTORY)

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

    def __setattr__(self, name, value):
        self[name] = value

class RequestContext(object):
    def __init__(self, service, operation):
        self.service = service
        self.operation = operation

    def execute(self):
        self.service.continue_execution(self)
 <INSERT_END> <|endoftext|> """
RequestContext stores state relevant to the current request, as well as
keeping track of the plugin execution order and providing a simple method
`advance` for calling the next plugin in the chain.
"""
import collections

class Container(collections.defaultdict):
    DEFAULT_FACTORY = lambda: None

    def __init__(self):
        super().__init__(self, Container.DEFAULT_FACTORY)

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

    def __setattr__(self, name, value):
        self[name] = value

class RequestContext(object):
    def __init__(self, service, operation):
        self.service = service
        self.operation = operation

    def execute(self):
        self.service.continue_execution(self)

Prompt:
Add building blocks Container, Context

These will be used for request/response dicts, as well as
containers for plugins to pass functions and values to the
operation function or other plugins.


#
# Copyright 2017-2021 European Centre for Medium-Range Weather Forecasts (ECMWF).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

__version__ = "0.9.9.2.dev0"

# cfgrib core API depends on the ECMWF ecCodes C-library only
from .cfmessage import CfMessage
from .dataset import Dataset, DatasetBuildError, open_container, open_file, open_from_index
from .messages import FileStream, Message

# NOTE: xarray is not a hard dependency, but let's provide helpers if it is available.
try:
    from .xarray_store import open_dataset, open_datasets
except ImportError:
    pass

Response:
<REPLACE_OLD> (
    Dataset,
    DatasetBuildError,
    open_container,
    open_file,
    open_fileindex,
    open_from_index,
)
from <REPLACE_NEW> Dataset, DatasetBuildError, open_container, open_file, open_from_index
from <REPLACE_END> <|endoftext|> #
# Copyright 2017-2021 European Centre for Medium-Range Weather Forecasts (ECMWF).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

__version__ = "0.9.9.2.dev0"

# cfgrib core API depends on the ECMWF ecCodes C-library only
from .cfmessage import CfMessage
from .dataset import Dataset, DatasetBuildError, open_container, open_file, open_from_index
from .messages import FileStream, Message

# NOTE: xarray is not a hard dependency, but let's provide helpers if it is available.
try:
    from .xarray_store import open_dataset, open_datasets
except ImportError:
    pass

Prompt:
Drop unused and dangerous entrypoint `open_fileindex`

#
# Copyright 2017-2021 European Centre for Medium-Range Weather Forecasts (ECMWF).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

__version__ = "0.9.9.2.dev0"

# cfgrib core API depends on the ECMWF ecCodes C-library only
from .cfmessage import CfMessage
from .dataset import (
    Dataset,
    DatasetBuildError,
    open_container,
    open_file,
    open_fileindex,
    open_from_index,
)
from .messages import FileStream, Message

# NOTE: xarray is not a hard dependency, but let's provide helpers if it is available.
try:
    from .xarray_store import open_dataset, open_datasets
except ImportError:
    pass


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

import logging

from .exceptions import PoyoException
from .parser import parse_string

__author__ = 'Raphael Pierzina'
__email__ = 'raphael@hackebrot.de'
__version__ = '0.3.0'

logging.getLogger(__name__).addHandler(logging.NullHandler())

__all__ = ['parse_string', 'PoyoException']

Add NullHandler to poyo root logger

Add NullHandler to poyo root logger

Response:
<REPLACE_OLD> -*-

from <REPLACE_NEW> -*-

import logging

from <REPLACE_END> <REPLACE_OLD> '0.3.0'

__all__ <REPLACE_NEW> '0.3.0'

logging.getLogger(__name__).addHandler(logging.NullHandler())

__all__ <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-

import logging

from .exceptions import PoyoException
from .parser import parse_string

__author__ = 'Raphael Pierzina'
__email__ = 'raphael@hackebrot.de'
__version__ = '0.3.0'

logging.getLogger(__name__).addHandler(logging.NullHandler())

__all__ = ['parse_string', 'PoyoException']

Prompt:
Add NullHandler to poyo root logger

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

from .exceptions import PoyoException
from .parser import parse_string

__author__ = 'Raphael Pierzina'
__email__ = 'raphael@hackebrot.de'
__version__ = '0.3.0'

__all__ = ['parse_string', 'PoyoException']


# Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#            http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

try:
    from django.conf.urls import patterns, handler500, url
# Fallback for Django versions < 1.4
except ImportError:
    from django.conf.urls.defaults import patterns, handler500, url

urlpatterns = patterns(
    'djangosaml2.views',
    url(r'^login/$', 'login', name='saml2_login'),
    url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'),
    url(r'^logout/$', 'logout', name='saml2_logout'),
    url(r'^ls/$', 'logout_service', name='saml2_ls'),
    url(r'^metadata/$', 'metadata', name='saml2_metadata'),
)

handler500 = handler500

Fix imports for Django 1.6 and above

Fix imports for Django 1.6 and above

Response:
<REPLACE_OLD> License.

from <REPLACE_NEW> License.

try:
    from django.conf.urls import patterns, handler500, url
# Fallback for Django versions < 1.4
except ImportError:
    from <REPLACE_END> <|endoftext|> # Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#            http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

try:
    from django.conf.urls import patterns, handler500, url
# Fallback for Django versions < 1.4
except ImportError:
    from django.conf.urls.defaults import patterns, handler500, url

urlpatterns = patterns(
    'djangosaml2.views',
    url(r'^login/$', 'login', name='saml2_login'),
    url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'),
    url(r'^logout/$', 'logout', name='saml2_logout'),
    url(r'^ls/$', 'logout_service', name='saml2_ls'),
    url(r'^metadata/$', 'metadata', name='saml2_metadata'),
)

handler500 = handler500

Prompt:
Fix imports for Django 1.6 and above

# Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#            http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from django.conf.urls.defaults import patterns, handler500, url

urlpatterns = patterns(
    'djangosaml2.views',
    url(r'^login/$', 'login', name='saml2_login'),
    url(r'^acs/$', 'assertion_consumer_service', name='saml2_acs'),
    url(r'^logout/$', 'logout', name='saml2_logout'),
    url(r'^ls/$', 'logout_service', name='saml2_ls'),
    url(r'^metadata/$', 'metadata', name='saml2_metadata'),
)

handler500 = handler500


import i18naddress
from django import template
from django.utils.translation import pgettext

register = template.Library()

@register.inclusion_tag("formatted_address.html")
def format_address(address, include_phone=True, inline=False, latin=False):
    address_data = address.as_data()
    address_data["name"] = (
        pgettext("Address data", "%(first_name)s %(last_name)s") % address_data
    )
    address_data["country_code"] = address_data["country"]
    address_data["street_address"] = pgettext(
        "Address data", "%(street_address_1)s\n" "%(street_address_2)s" % address_data
    )
    address_lines = i18naddress.format_address(address_data, latin).split("\n")
    if include_phone and address.phone:
        address_lines.append(str(address.phone))
    return {"address_lines": address_lines, "inline": inline}

Fix phone number formatting in emails

Fix phone number formatting in emails

Response:
<REPLACE_OLD> address_lines.append(address.phone)
 <REPLACE_NEW> address_lines.append(str(address.phone))
 <REPLACE_END> <|endoftext|> import i18naddress
from django import template
from django.utils.translation import pgettext

register = template.Library()

@register.inclusion_tag("formatted_address.html")
def format_address(address, include_phone=True, inline=False, latin=False):
    address_data = address.as_data()
    address_data["name"] = (
        pgettext("Address data", "%(first_name)s %(last_name)s") % address_data
    )
    address_data["country_code"] = address_data["country"]
    address_data["street_address"] = pgettext(
        "Address data", "%(street_address_1)s\n" "%(street_address_2)s" % address_data
    )
    address_lines = i18naddress.format_address(address_data, latin).split("\n")
    if include_phone and address.phone:
        address_lines.append(str(address.phone))
    return {"address_lines": address_lines, "inline": inline}

Prompt:
Fix phone number formatting in emails

import i18naddress
from django import template
from django.utils.translation import pgettext

register = template.Library()

@register.inclusion_tag("formatted_address.html")
def format_address(address, include_phone=True, inline=False, latin=False):
    address_data = address.as_data()
    address_data["name"] = (
        pgettext("Address data", "%(first_name)s %(last_name)s") % address_data
    )
    address_data["country_code"] = address_data["country"]
    address_data["street_address"] = pgettext(
        "Address data", "%(street_address_1)s\n" "%(street_address_2)s" % address_data
    )
    address_lines = i18naddress.format_address(address_data, latin).split("\n")
    if include_phone and address.phone:
        address_lines.append(address.phone)
    return {"address_lines": address_lines, "inline": inline}


import json

from django import http
from django.views.decorators.http import require_POST

from account.models import EmailAddress
from django.contrib.auth.decorators import login_required

from kaleo.forms import InviteForm
from kaleo.models import JoinInvitation

@login_required
@require_POST
def invite(request):
    form = InviteForm(request.POST)
    if form.is_valid():
        email = form.cleaned_data["email_address"]
        if EmailAddress.objects.filter(email=email, verified=True).exists():
            data = {"status": "ERROR", "errors": '

%s is already on this site

' % email}
        elif JoinInvitation.objects.filter(from_user=request.user, signup_code__email=email).exists():
            data = {"status": "ERROR", "errors": '

You have already invited %s

' % email}
        else:
            JoinInvitation.invite(request.user, email)
            data = {
                "status": "OK",
                "email": email,
                "invitations_remaining": request.user.invitationstat.invites_remaining()
            }
    else:
        data = {"status": "ERROR", "errors": str(form.errors["email_address"])}
    return http.HttpResponse(json.dumps(data), content_type="application/json")

Response:
<REPLACE_OLD> from <REPLACE_NEW> import json

from <REPLACE_END> <DELETE> django.utils import simplejson as json
from <DELETE_END> <REPLACE_OLD> require_http_methods

from <REPLACE_NEW> require_POST

from <REPLACE_END> <REPLACE_OLD> EmailAddress

from <REPLACE_NEW> EmailAddress
from django.contrib.auth.decorators import login_required

from <REPLACE_END> <REPLACE_OLD> JoinInvitation

@require_http_methods(["POST"])
def <REPLACE_NEW> JoinInvitation

@login_required
@require_POST
def <REPLACE_END> <DELETE>    if not request.user.is_authenticated():
        data = {"status": "ERROR", "message": "not authenticated"}
        return http.HttpResponseBadRequest(json.dumps(data), content_type="application/json")
 <DELETE_END> <|endoftext|> import json

from django import http
from django.views.decorators.http import require_POST

from account.models import EmailAddress
from django.contrib.auth.decorators import login_required

from kaleo.forms import InviteForm
from kaleo.models import JoinInvitation

@login_required
@require_POST
def invite(request):
    form = InviteForm(request.POST)
    if form.is_valid():
        email = form.cleaned_data["email_address"]
        if EmailAddress.objects.filter(email=email, verified=True).exists():
            data = {"status": "ERROR", "errors": '<ul class="errorlist"><li>%s is already on this site</li></ul>' % email}
        elif JoinInvitation.objects.filter(from_user=request.user, signup_code__email=email).exists():
            data = {"status": "ERROR", "errors": '<ul class="errorlist"><li>You have already invited %s</li></ul>' % email}
        else:
            JoinInvitation.invite(request.user, email)
            data = {
                "status": "OK",
                "email": email,
                "invitations_remaining": request.user.invitationstat.invites_remaining()
            }
    else:
        data = {"status": "ERROR", "errors": str(form.errors["email_address"])}
    return http.HttpResponse(json.dumps(data), content_type="application/json")

Prompt:
Update view to use different imports/decorators

1. We can generally expect the json module to be
   available now, so no need to use what ships with
   django
2. require_POST is just simpler and more direct
3. Using login_required is clearer as well instead
   of using custom logic.
from django import http
from django.utils import simplejson as json
from django.views.decorators.http import require_http_methods

from account.models import EmailAddress

from kaleo.forms import InviteForm
from kaleo.models import JoinInvitation

@require_http_methods(["POST"])
def invite(request):
    if not request.user.is_authenticated():
        data = {"status": "ERROR", "message": "not authenticated"}
        return http.HttpResponseBadRequest(json.dumps(data), content_type="application/json")
    form = InviteForm(request.POST)
    if form.is_valid():
        email = form.cleaned_data["email_address"]
        if EmailAddress.objects.filter(email=email, verified=True).exists():
            data = {"status": "ERROR", "errors": '

%s is already on this site

' % email}
        elif JoinInvitation.objects.filter(from_user=request.user, signup_code__email=email).exists():
            data = {"status": "ERROR", "errors": '

You have already invited %s

' % email}
        else:
            JoinInvitation.invite(request.user, email)
            data = {
                "status": "OK",
                "email": email,
                "invitations_remaining": request.user.invitationstat.invites_remaining()
            }
    else:
        data = {"status": "ERROR", "errors": str(form.errors["email_address"])}
    return http.HttpResponse(json.dumps(data), content_type="application/json")


__version_info__ = (1, 3, 0, 'dev')

# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join([str(i) for i in __version_info__[:-1]])
if __version_info__[-1] is not None:
    __version__ += ('-%s' % (__version_info__[-1],))

# context processor to add version to the template environment
def context_extras(request):
    return {
        # software version
        'SW_VERSION': __version__
    }

Set develop version to 1.3-dev

Set develop version to 1.3-dev

Response:
<REPLACE_OLD> 2, <REPLACE_NEW> 3, <REPLACE_END> <REPLACE_OLD> None)

# <REPLACE_NEW> 'dev')

# <REPLACE_END> <|endoftext|> __version_info__ = (1, 3, 0, 'dev')

# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join([str(i) for i in __version_info__[:-1]])
if __version_info__[-1] is not None:
    __version__ += ('-%s' % (__version_info__[-1],))

# context processor to add version to the template environment
def context_extras(request):
    return {
        # software version
        'SW_VERSION': __version__
    }

Prompt:
Set develop version to 1.3-dev

__version_info__ = (1, 2, 0, None)

# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join([str(i) for i in __version_info__[:-1]])
if __version_info__[-1] is not None:
    __version__ += ('-%s' % (__version_info__[-1],))

# context processor to add version to the template environment
def context_extras(request):
    return {
        # software version
        'SW_VERSION': __version__
    }


# -*- coding: utf-8 -*-
##############################################################################
#
#    Copyright (C) 2017 Compassion CH (http://www.compassion.ch)
#    Releasing children from poverty in Jesus' name
#    @author: Emanuel Cino <ecino@compassion.ch>
#
#    The licence is in the file __manifest__.py
#
##############################################################################

from openupgradelib import openupgrade

@openupgrade.migrate(use_env=True)
def migrate(env, version):
    if not version:
        return

    cr = env.cr
    # Remove end reason on active sponsorships
    cr.execute("""
        UPDATE recurring_contract
        SET end_reason = NULL
        WHERE STATE NOT IN
        ('terminated', 'cancelled');
    """)
    # Remove waiting_welcome state of non sponsorship contracts
    # or old contracts
    cr.execute("""
            UPDATE recurring_contract
            SET sds_state = 'active'
            WHERE sds_state = 'waiting_welcome'
            AND (type not in ('S', 'SC')
                 OR sds_state_date < current_date - INTERVAL '15 days');
        """)

Response:
<INSERT>    # Remove waiting_welcome state of non sponsorship contracts
    # or old contracts
    cr.execute("""
            UPDATE recurring_contract
            SET sds_state = 'active'
            WHERE sds_state = 'waiting_welcome'
            AND (type not in ('S', 'SC')
                 OR sds_state_date < current_date - INTERVAL '15 days');
        """)
 <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
##############################################################################
#
#    Copyright (C) 2017 Compassion CH (http://www.compassion.ch)
#    Releasing children from poverty in Jesus' name
#    @author: Emanuel Cino <ecino@compassion.ch>
#
#    The licence is in the file __manifest__.py
#
##############################################################################

from openupgradelib import openupgrade

@openupgrade.migrate(use_env=True)
def migrate(env, version):
    if not version:
        return

    cr = env.cr
    # Remove end reason on active sponsorships
    cr.execute("""
        UPDATE recurring_contract
        SET end_reason = NULL
        WHERE STATE NOT IN
        ('terminated', 'cancelled');
    """)
    # Remove waiting_welcome state of non sponsorship contracts
    # or old contracts
    cr.execute("""
            UPDATE recurring_contract
            SET sds_state = 'active'
            WHERE sds_state = 'waiting_welcome'
            AND (type not in ('S', 'SC')
                 OR sds_state_date < current_date - INTERVAL '15 days');
        """)

Prompt:
FIX only sponsorships can go through waiting_welcome state

# -*- coding: utf-8 -*-
##############################################################################
#
#    Copyright (C) 2017 Compassion CH (http://www.compassion.ch)
#    Releasing children from poverty in Jesus' name
#    @author: Emanuel Cino <ecino@compassion.ch>
#
#    The licence is in the file __manifest__.py
#
##############################################################################

from openupgradelib import openupgrade

@openupgrade.migrate(use_env=True)
def migrate(env, version):
    if not version:
        return

    cr = env.cr
    # Remove end reason on active sponsorships
    cr.execute("""
        UPDATE recurring_contract
        SET end_reason = NULL
        WHERE STATE NOT IN
        ('terminated', 'cancelled');
    """)


#!/usr/bin/python
from __future__ import print_function
import argparse
import re

time_re = re.compile(r"^\s*#?\s*([0-9]+(?:\.[0-9]+)?)\s+\"")
first_num_re = re.compile(r"([0-9]+(?:\.[0-9]+)?)")

def adjust_lines(lines, adjust):
  for line in lines:
    match = re.match(time_re, line)
    if match:
      time = float(match.group(1)) + adjust
      print(re.sub(first_num_re, str(time), line, 1), end='')
    else:
      print(line, end='')

def main():
  parser = argparse.ArgumentParser(
      description="A utility to uniformly adjust times in an act timeline file")
  parser.add_argument('--file', required=True, type=argparse.FileType('r', encoding="utf8"),
      help="The timeline file to adjust times in")
  parser.add_argument('--adjust', required=True, type=float,
      help="The amount of time to adjust each entry by")

  args = parser.parse_args()
  adjust_lines(args.file, args.adjust)

if __name__ == "__main__":
  main()

Response:
<REPLACE_OLD> 0),
 <REPLACE_NEW> encoding="utf8"),
 <REPLACE_END> <|endoftext|> #!/usr/bin/python
from __future__ import print_function
import argparse
import re

time_re = re.compile(r"^\s*#?\s*([0-9]+(?:\.[0-9]+)?)\s+\"")
first_num_re = re.compile(r"([0-9]+(?:\.[0-9]+)?)")

def adjust_lines(lines, adjust):
  for line in lines:
    match = re.match(time_re, line)
    if match:
      time = float(match.group(1)) + adjust
      print(re.sub(first_num_re, str(time), line, 1), end='')
    else:
      print(line, end='')

def main():
  parser = argparse.ArgumentParser(
      description="A utility to uniformly adjust times in an act timeline file")
  parser.add_argument('--file', required=True, type=argparse.FileType('r', encoding="utf8"),
      help="The timeline file to adjust times in")
  parser.add_argument('--adjust', required=True, type=float,
      help="The amount of time to adjust each entry by")

  args = parser.parse_args()
  adjust_lines(args.file, args.adjust)

if __name__ == "__main__":
  main()

Prompt:
Fix timeline adjust not being able to load Windows files

#!/usr/bin/python
from __future__ import print_function
import argparse
import re

time_re = re.compile(r"^\s*#?\s*([0-9]+(?:\.[0-9]+)?)\s+\"")
first_num_re = re.compile(r"([0-9]+(?:\.[0-9]+)?)")

def adjust_lines(lines, adjust):
  for line in lines:
    match = re.match(time_re, line)
    if match:
      time = float(match.group(1)) + adjust
      print(re.sub(first_num_re, str(time), line, 1), end='')
    else:
      print(line, end='')

def main():
  parser = argparse.ArgumentParser(
      description="A utility to uniformly adjust times in an act timeline file")
  parser.add_argument('--file', required=True, type=argparse.FileType('r', 0),
      help="The timeline file to adjust times in")
  parser.add_argument('--adjust', required=True, type=float,
      help="The amount of time to adjust each entry by")

  args = parser.parse_args()
  adjust_lines(args.file, args.adjust)

if __name__ == "__main__":
  main()


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

from setuptools import setup

setup(name='sophiabus230',
      version='0.5',
      description='Module to get the timetable of the Sophia Antipolis bus line 230',
      url='http://github.com/paraita/sophiabus230',
      author='Paraita Wohler',
      author_email='paraita.wohler@gmail.com',
      license='MIT',
      packages=['sophiabus230'],
      install_requires=[
          'beautifulsoup4',
          'python-dateutil',
          'future'
      ],
      test_suite='nose.collector',
      tests_require=[
          'mock',
          'nose',
          'coverage',
          'coveralls'
      ],
      zip_safe=False)

Update package version for Pypi

Update package version for Pypi

Response:
<REPLACE_OLD> version='0.4',
 <REPLACE_NEW> version='0.5',
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-

from setuptools import setup

setup(name='sophiabus230',
      version='0.5',
      description='Module to get the timetable of the Sophia Antipolis bus line 230',
      url='http://github.com/paraita/sophiabus230',
      author='Paraita Wohler',
      author_email='paraita.wohler@gmail.com',
      license='MIT',
      packages=['sophiabus230'],
      install_requires=[
          'beautifulsoup4',
          'python-dateutil',
          'future'
      ],
      test_suite='nose.collector',
      tests_require=[
          'mock',
          'nose',
          'coverage',
          'coveralls'
      ],
      zip_safe=False)

Prompt:
Update package version for Pypi

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

from setuptools import setup

setup(name='sophiabus230',
      version='0.4',
      description='Module to get the timetable of the Sophia Antipolis bus line 230',
      url='http://github.com/paraita/sophiabus230',
      author='Paraita Wohler',
      author_email='paraita.wohler@gmail.com',
      license='MIT',
      packages=['sophiabus230'],
      install_requires=[
          'beautifulsoup4',
          'python-dateutil',
          'future'
      ],
      test_suite='nose.collector',
      tests_require=[
          'mock',
          'nose',
          'coverage',
          'coveralls'
      ],
      zip_safe=False)


from django.views.generic import TemplateView

from competition.models import Competition

class HomePageView(TemplateView):
    template_name = "home/home.html"

    def get_context_data(self, **kwargs):
        context = super(HomePageView, self).get_context_data(**kwargs)

        if not self.request.user.is_anonymous():
            my_competitions = Competition.objects.user_registered(self.request.user)
            context["registered_competitions"] = my_competitions.exclude(is_running=False, is_open=False)
            context["closed_competitions"] = my_competitions.filter(is_running=False, is_open=False)
        return context

Response:
<INSERT>   <INSERT_END> <REPLACE_OLD> self).get_context_data(**kwargs)
 <REPLACE_NEW> self).get_context_data(**kwargs)

        if not self.request.user.is_anonymous():
       <REPLACE_END> <INSERT>       <INSERT_END> <INSERT>       <INSERT_END> <INSERT>   <INSERT_END> <|endoftext|> from django.views.generic import TemplateView

from competition.models import Competition

class HomePageView(TemplateView):
    template_name = "home/home.html"

    def get_context_data(self, **kwargs):
        context = super(HomePageView, self).get_context_data(**kwargs)

        if not self.request.user.is_anonymous():
            my_competitions = Competition.objects.user_registered(self.request.user)
            context["registered_competitions"] = my_competitions.exclude(is_running=False, is_open=False)
            context["closed_competitions"] = my_competitions.filter(is_running=False, is_open=False)
        return context

Prompt:
Check if user is not anonymous on homepage

from django.views.generic import TemplateView

from competition.models import Competition

class HomePageView(TemplateView):
    template_name = "home/home.html"

    def get_context_data(self, **kwargs):
      context = super(HomePageView, self).get_context_data(**kwargs)
      my_competitions = Competition.objects.user_registered(self.request.user)
      context["registered_competitions"] = my_competitions.exclude(is_running=False, is_open=False)
      context["closed_competitions"] = my_competitions.filter(is_running=False, is_open=False)
      return context


# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2017
import sys
import streamsx.topology.context

def standalone(test, topo):
    rc = streamsx.topology.context.submit("STANDALONE", topo)
    test.assertEqual(0, rc['return_code'])

Response:
<REPLACE_OLD> rc)

 <REPLACE_NEW> rc['return_code'])

 <REPLACE_END> <|endoftext|> # Licensed Materials - Property of IBM
# Copyright IBM Corp. 2017
import sys
import streamsx.topology.context

def standalone(test, topo):
    rc = streamsx.topology.context.submit("STANDALONE", topo)
    test.assertEqual(0, rc['return_code'])

Prompt:
Return value of submit is now a json dict

# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2017
import sys
import streamsx.topology.context

def standalone(test, topo):
    rc = streamsx.topology.context.submit("STANDALONE", topo)
    test.assertEqual(0, rc)


# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Single source of truth for dsub's version.

This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.

The version should follow formatting requirements specified in PEP-440.
 - https://www.python.org/dev/peps/pep-0440

A typical release sequence will be versioned as:
  0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""

DSUB_VERSION = '0.3.2.dev0'

Update dsub version to 0.3.2.dev0

Response:
<REPLACE_OLD> '0.3.1'
 <REPLACE_NEW> '0.3.2.dev0'
 <REPLACE_END> <|endoftext|> # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Single source of truth for dsub's version.

This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.

The version should follow formatting requirements specified in PEP-440.
 - https://www.python.org/dev/peps/pep-0440

A typical release sequence will be versioned as:
  0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""

DSUB_VERSION = '0.3.2.dev0'

Prompt:
Update dsub version to 0.3.2.dev0

PiperOrigin-RevId: 243855458

# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Single source of truth for dsub's version.

This must remain small and dependency-free so that any dsub module may
import it without creating circular dependencies. Note that this module
is parsed as a text file by setup.py and changes to the format of this
file could break setup.py.

The version should follow formatting requirements specified in PEP-440.
 - https://www.python.org/dev/peps/pep-0440

A typical release sequence will be versioned as:
  0.1.3.dev0 -> 0.1.3 -> 0.1.4.dev0 -> ...
"""

DSUB_VERSION = '0.3.1'


#!/usr/bin/env python

import os
import urllib
import zipfile

script_path = os.path.dirname(os.path.realpath(__file__))
packer_archive_path = script_path + "/packer.zip"
bin_path = script_path + "/bin"

if not os.path.isfile(bin_path + "/packer"):
    if not os.path.exists(bin_path):
        os.makedirs(bin_path)
    try:
        urllib.urlretrieve("https://dl.bintray.com/mitchellh/packer/packer_0.8.6_linux_amd64.zip", packer_archive_path)
        with zipfile.ZipFile(packer_archive_path, "r") as packer_archive:
            packer_archive.extractall(path=bin_path)
    finally:
        os.remove(packer_archive_path)

for root, subdirectories, files in os.walk(bin_path):
    for f in files:
        os.chmod(root +  "/" + f, 755)

Fix false positive octal syntax warning

Fix false positive octal syntax warning

Response:
<REPLACE_OLD> os.chmod("%s/%s" % (root, f), 0755)

 <REPLACE_NEW> os.chmod(root +  "/" + f, 755)

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

import os
import urllib
import zipfile

script_path = os.path.dirname(os.path.realpath(__file__))
packer_archive_path = script_path + "/packer.zip"
bin_path = script_path + "/bin"

if not os.path.isfile(bin_path + "/packer"):
    if not os.path.exists(bin_path):
        os.makedirs(bin_path)
    try:
        urllib.urlretrieve("https://dl.bintray.com/mitchellh/packer/packer_0.8.6_linux_amd64.zip", packer_archive_path)
        with zipfile.ZipFile(packer_archive_path, "r") as packer_archive:
            packer_archive.extractall(path=bin_path)
    finally:
        os.remove(packer_archive_path)

for root, subdirectories, files in os.walk(bin_path):
    for f in files:
        os.chmod(root +  "/" + f, 755)

Prompt:
Fix false positive octal syntax warning

#!/usr/bin/env python

import os
import urllib
import zipfile

script_path = os.path.dirname(os.path.realpath(__file__))
packer_archive_path = script_path + "/packer.zip"
bin_path = script_path + "/bin"

if not os.path.isfile(bin_path + "/packer"):
    if not os.path.exists(bin_path):
        os.makedirs(bin_path)
    try:
        urllib.urlretrieve("https://dl.bintray.com/mitchellh/packer/packer_0.8.6_linux_amd64.zip", packer_archive_path)
        with zipfile.ZipFile(packer_archive_path, "r") as packer_archive:
            packer_archive.extractall(path=bin_path)
    finally:
        os.remove(packer_archive_path)

for root, subdirectories, files in os.walk(bin_path):
    for f in files:
        os.chmod("%s/%s" % (root, f), 0755)


import os
import webapp2
import logging

import handlers

debug = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
loglevel = logging.DEBUG if debug else logging.INFO
logging.getLogger().setLevel(loglevel)

task_app = webapp2.WSGIApplication([
    ('/task/index', handlers.IndexTaskHandler),
    ('/task/torrent', handlers.TorrentTaskHandler),
    ('/task/update_feeds', handlers.FeedTaskHandler),
    ('/task/cleanup', handlers.JanitorTaskHandler)
], debug=debug)

manage_app = webapp2.WSGIApplication([
    ('/manage/', handlers.DashboardHandler),
], debug=debug)

Response:
<REPLACE_OLD> webapp2

import <REPLACE_NEW> webapp2
import logging

import <REPLACE_END> <REPLACE_OLD> '').startswith('Dev')

task_app <REPLACE_NEW> '').startswith('Dev')
loglevel = logging.DEBUG if debug else logging.INFO
logging.getLogger().setLevel(loglevel)

task_app <REPLACE_END> <|endoftext|> import os
import webapp2
import logging

import handlers

debug = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')
loglevel = logging.DEBUG if debug else logging.INFO
logging.getLogger().setLevel(loglevel)

task_app = webapp2.WSGIApplication([
    ('/task/index', handlers.IndexTaskHandler),
    ('/task/torrent', handlers.TorrentTaskHandler),
    ('/task/update_feeds', handlers.FeedTaskHandler),
    ('/task/cleanup', handlers.JanitorTaskHandler)
], debug=debug)

manage_app = webapp2.WSGIApplication([
    ('/manage/', handlers.DashboardHandler),
], debug=debug)

Prompt:
Set logging level depenging on environment

import os
import webapp2

import handlers

debug = os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')

task_app = webapp2.WSGIApplication([
    ('/task/index', handlers.IndexTaskHandler),
    ('/task/torrent', handlers.TorrentTaskHandler),
    ('/task/update_feeds', handlers.FeedTaskHandler),
    ('/task/cleanup', handlers.JanitorTaskHandler)
], debug=debug)

manage_app = webapp2.WSGIApplication([
    ('/manage/', handlers.DashboardHandler),
], debug=debug)