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

VERSION = '0.9.4pre'

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

VERSION = '0.9.4pre'

Prompt:
Add a -vvv mode to log when tests are queued for running.

If one is running a bunch of tests in parallel and something
is not working right, it can be useful to see which tests are
currently executing at the same time. There isn't a great way
to do this in typ, because we don't know when tests are actually
picked up for execution by the child processes, but we can at
least log which tests has been queued for running.

This patch adds a -vvv option (verbose=3). This will make
the test log twice as long, since we will now log lines for
when every test starts and stops, but at least that can help
with debugging.

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

VERSION = '0.9.4'


import unittest
import os
from subprocess import check_call
from sh import ls

mountpoint = '/tmp/spotifile_test_mount'
class SpotifileTestClass(unittest.TestCase):
	@classmethod
	def setUpClass(cls):
		if not os.path.exists(mountpoint):
			os.mkdir(mountpoint)

	@classmethod
	def tearDownClass(cls):
		if os.path.exists(mountpoint):
			os.rmdir(mountpoint)

	def setUp(self):
		check_call(['./spotifile', mountpoint])

	def tearDown(self):
		check_call(['fusermount', '-u', mountpoint])

	def test_ls(self):
		assert 'connection' in ls(mountpoint)

tests: Add simple test to check that we populate the root as expected

Signed-off-by: Anton Lofgren <64e2cb85477d4abaea4b354af986fde12a3e64f3@op5.com>

Response:
<REPLACE_OLD>  <REPLACE_NEW> import unittest
import os
from subprocess import check_call
from sh import ls

mountpoint = '/tmp/spotifile_test_mount'
class SpotifileTestClass(unittest.TestCase):
	@classmethod
	def setUpClass(cls):
		if not os.path.exists(mountpoint):
			os.mkdir(mountpoint)

	@classmethod
	def tearDownClass(cls):
		if os.path.exists(mountpoint):
			os.rmdir(mountpoint)

	def setUp(self):
		check_call(['./spotifile', mountpoint])

	def tearDown(self):
		check_call(['fusermount', '-u', mountpoint])

	def test_ls(self):
		assert 'connection' in ls(mountpoint)
 <REPLACE_END> <|endoftext|> import unittest
import os
from subprocess import check_call
from sh import ls

mountpoint = '/tmp/spotifile_test_mount'
class SpotifileTestClass(unittest.TestCase):
	@classmethod
	def setUpClass(cls):
		if not os.path.exists(mountpoint):
			os.mkdir(mountpoint)

	@classmethod
	def tearDownClass(cls):
		if os.path.exists(mountpoint):
			os.rmdir(mountpoint)

	def setUp(self):
		check_call(['./spotifile', mountpoint])

	def tearDown(self):
		check_call(['fusermount', '-u', mountpoint])

	def test_ls(self):
		assert 'connection' in ls(mountpoint)

Prompt:
tests: Add simple test to check that we populate the root as expected

Signed-off-by: Anton Lofgren <64e2cb85477d4abaea4b354af986fde12a3e64f3@op5.com>


"""Configuration for Django system."""

__version__ = "0.16.0"
__version_info__ = tuple(
    [
        int(num) if num.isdigit() else num
        for num in __version__.replace("-", ".", 1).split(".")
    ]
)

Increment version number to 0.16.0

Increment version number to 0.16.0

Response:
<REPLACE_OLD> "0.15.2"
__version_info__ <REPLACE_NEW> "0.16.0"
__version_info__ <REPLACE_END> <|endoftext|> """Configuration for Django system."""

__version__ = "0.16.0"
__version_info__ = tuple(
    [
        int(num) if num.isdigit() else num
        for num in __version__.replace("-", ".", 1).split(".")
    ]
)

Prompt:
Increment version number to 0.16.0

"""Configuration for Django system."""

__version__ = "0.15.2"
__version_info__ = tuple(
    [
        int(num) if num.isdigit() else num
        for num in __version__.replace("-", ".", 1).split(".")
    ]
)


#!/usr/bin/env python

import pytest
from butter.inotify import watch

from subprocess import Popen
from tempfile import TemporaryDirectory
from time import sleep
import os

def test_watch():
    FILENAME = 'inotify_test'
    with TemporaryDirectory() as tmp_dir:
        filename = os.path.join(tmp_dir, FILENAME)

        proc = Popen('sleep 0.04 ; touch {}'.format(filename), shell=True)

        event = watch(tmp_dir)

        proc.wait()

Add tests for watch function

Add tests for watch function

Response:
<INSERT> #!/usr/bin/env python

import pytest
from butter.inotify import watch

from subprocess import Popen
from tempfile import TemporaryDirectory
from time import sleep
import os

def test_watch():
 <INSERT_END> <INSERT>   FILENAME = 'inotify_test'
    with TemporaryDirectory() as tmp_dir:
        filename = os.path.join(tmp_dir, FILENAME)

        proc = Popen('sleep 0.04 ; touch {}'.format(filename), shell=True)

        event = watch(tmp_dir)

        proc.wait()
 <INSERT_END> <|endoftext|> #!/usr/bin/env python

import pytest
from butter.inotify import watch

from subprocess import Popen
from tempfile import TemporaryDirectory
from time import sleep
import os

def test_watch():
    FILENAME = 'inotify_test'
    with TemporaryDirectory() as tmp_dir:
        filename = os.path.join(tmp_dir, FILENAME)

        proc = Popen('sleep 0.04 ; touch {}'.format(filename), shell=True)

        event = watch(tmp_dir)

        proc.wait()

Prompt: Add tests for watch function


# XXX those are needed by the scons command only...
from core.misc import get_scons_path, get_scons_build_dir, \
                      get_scons_configres_dir, get_scons_configres_filename
from core.libinfo import get_paths as scons_get_paths

# XXX those should not be needed by the scons command only...
from core.extension import get_python_inc, get_pythonlib_dir

# Those functions really belong to the public API
from core.numpyenv import GetNumpyEnvironment
from core.libinfo_scons import NumpyCheckLibAndHeader

from checkers import CheckF77BLAS, CheckCBLAS, CheckCLAPACK, CheckF77LAPACK, CheckFFT
from fortran_scons import CheckF77Mangling
#import tools

# XXX: this is ugly, better find the mathlibs with a checker
# XXX: this had nothing to do here, too...
def scons_get_mathlib(env):
    from numpy.distutils.misc_util import get_mathlibs
    path_list = scons_get_paths(env['include_bootstrap']) + [None]
    for i in path_list:
        try:
            mlib =  get_mathlibs(i)
            return mlib
        except IOError:
            pass
    raise RuntimeError("FIXME: no mlib found ?")

Response:
<REPLACE_OLD> get_scons_configres_filename

# <REPLACE_NEW> get_scons_configres_filename
from core.libinfo import get_paths as scons_get_paths

# <REPLACE_END> <REPLACE_OLD> tools
 <REPLACE_NEW> tools

# XXX: this is ugly, better find the mathlibs with a checker
# XXX: this had nothing to do here, too...
def scons_get_mathlib(env):
    from numpy.distutils.misc_util import get_mathlibs
    path_list = scons_get_paths(env['include_bootstrap']) + [None]
    for i in path_list:
        try:
            mlib =  get_mathlibs(i)
            return mlib
        except IOError:
            pass
    raise RuntimeError("FIXME: no mlib found ?")

 <REPLACE_END> <|endoftext|> # XXX those are needed by the scons command only...
from core.misc import get_scons_path, get_scons_build_dir, \
                      get_scons_configres_dir, get_scons_configres_filename
from core.libinfo import get_paths as scons_get_paths

# XXX those should not be needed by the scons command only...
from core.extension import get_python_inc, get_pythonlib_dir

# Those functions really belong to the public API
from core.numpyenv import GetNumpyEnvironment
from core.libinfo_scons import NumpyCheckLibAndHeader

from checkers import CheckF77BLAS, CheckCBLAS, CheckCLAPACK, CheckF77LAPACK, CheckFFT
from fortran_scons import CheckF77Mangling
#import tools

# XXX: this is ugly, better find the mathlibs with a checker
# XXX: this had nothing to do here, too...
def scons_get_mathlib(env):
    from numpy.distutils.misc_util import get_mathlibs
    path_list = scons_get_paths(env['include_bootstrap']) + [None]
    for i in path_list:
        try:
            mlib =  get_mathlibs(i)
            return mlib
        except IOError:
            pass
    raise RuntimeError("FIXME: no mlib found ?")

Prompt:
Add more missing functions in numscons namespace
# XXX those are needed by the scons command only...
from core.misc import get_scons_path, get_scons_build_dir, \
                      get_scons_configres_dir, get_scons_configres_filename

# XXX those should not be needed by the scons command only...
from core.extension import get_python_inc, get_pythonlib_dir

# Those functions really belong to the public API
from core.numpyenv import GetNumpyEnvironment
from core.libinfo_scons import NumpyCheckLibAndHeader

from checkers import CheckF77BLAS, CheckCBLAS, CheckCLAPACK, CheckF77LAPACK, CheckFFT
from fortran_scons import CheckF77Mangling
#import tools


#!/usr/bin/env python

from os.path import dirname, abspath
import sys

from django.conf import settings

if not settings.configured:
    from django import VERSION
    settings_dict = dict(
        INSTALLED_APPS=(
            'localeurl',
            'django.contrib.sites', # for sitemap test
            ),
        ROOT_URLCONF='localeurl.tests.test_urls',
        )
    if VERSION >= (1, 2):
        settings_dict["DATABASES"] = {
            "default": {
                "ENGINE": "django.db.backends.sqlite3"
                }}
    else:
        settings_dict["DATABASE_ENGINE"] = "sqlite3"

    settings.configure(**settings_dict)

def runtests(*test_args):
    if not test_args:
        test_args = ['localeurl']
    parent = dirname(abspath(__file__))
    sys.path.insert(0, parent)
    try:
        from django.test.simple import DjangoTestSuiteRunner
        def run_tests(test_args, verbosity, interactive):
            runner = DjangoTestSuiteRunner(
                verbosity=verbosity, interactive=interactive)
            return runner.run_tests(test_args)
    except ImportError:
        # for Django versions that don't have DjangoTestSuiteRunner
        from django.test.simple import run_tests
    failures = run_tests(test_args, verbosity=1, interactive=True)
    sys.exit(failures)

if __name__ == '__main__':
    runtests(*sys.argv[1:])

Response:
<INSERT>            'django.contrib.sites', # for sitemap test
 <INSERT_END> <|endoftext|> #!/usr/bin/env python

from os.path import dirname, abspath
import sys

from django.conf import settings

if not settings.configured:
    from django import VERSION
    settings_dict = dict(
        INSTALLED_APPS=(
            'localeurl',
            'django.contrib.sites', # for sitemap test
            ),
        ROOT_URLCONF='localeurl.tests.test_urls',
        )
    if VERSION >= (1, 2):
        settings_dict["DATABASES"] = {
            "default": {
                "ENGINE": "django.db.backends.sqlite3"
                }}
    else:
        settings_dict["DATABASE_ENGINE"] = "sqlite3"

    settings.configure(**settings_dict)

def runtests(*test_args):
    if not test_args:
        test_args = ['localeurl']
    parent = dirname(abspath(__file__))
    sys.path.insert(0, parent)
    try:
        from django.test.simple import DjangoTestSuiteRunner
        def run_tests(test_args, verbosity, interactive):
            runner = DjangoTestSuiteRunner(
                verbosity=verbosity, interactive=interactive)
            return runner.run_tests(test_args)
    except ImportError:
        # for Django versions that don't have DjangoTestSuiteRunner
        from django.test.simple import run_tests
    failures = run_tests(test_args, verbosity=1, interactive=True)
    sys.exit(failures)

if __name__ == '__main__':
    runtests(*sys.argv[1:])

Prompt:
Include contrib.sites when running tests; needed for sitemaps in Django >= 1.2.

#!/usr/bin/env python

from os.path import dirname, abspath
import sys

from django.conf import settings

if not settings.configured:
    from django import VERSION
    settings_dict = dict(
        INSTALLED_APPS=(
            'localeurl',
            ),
        ROOT_URLCONF='localeurl.tests.test_urls',
        )
    if VERSION >= (1, 2):
        settings_dict["DATABASES"] = {
            "default": {
                "ENGINE": "django.db.backends.sqlite3"
                }}
    else:
        settings_dict["DATABASE_ENGINE"] = "sqlite3"

    settings.configure(**settings_dict)

def runtests(*test_args):
    if not test_args:
        test_args = ['localeurl']
    parent = dirname(abspath(__file__))
    sys.path.insert(0, parent)
    try:
        from django.test.simple import DjangoTestSuiteRunner
        def run_tests(test_args, verbosity, interactive):
            runner = DjangoTestSuiteRunner(
                verbosity=verbosity, interactive=interactive)
            return runner.run_tests(test_args)
    except ImportError:
        # for Django versions that don't have DjangoTestSuiteRunner
        from django.test.simple import run_tests
    failures = run_tests(test_args, verbosity=1, interactive=True)
    sys.exit(failures)

if __name__ == '__main__':
    runtests(*sys.argv[1:])


from setuptools import setup

setup(
    name='bwapi',

    version='3.2.0',

    description='A software development kit for the Brandwatch API',

    url='https://github.com/BrandwatchLtd/api_sdk',

    author='Amy Barker, Jamie Lebovics, Paul Siegel and Jessica Bowden',
    author_email='amyb@brandwatch.com, paul@brandwatch.com, jess@brandwatch.com',

    license='License :: OSI Approved :: MIT License',

    classifiers=[

        'Development Status :: 5 - Production/Stable',

        'Intended Audience :: Developers',

        'License :: OSI Approved :: MIT License',

        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7'
    ],

    py_modules=['bwproject', 'bwresources', 'bwdata', 'filters'],

    scripts=['authenticate.py'],

    install_requires=['requests'],

    tests_require=['responses']

)

Response:
<INSERT> scripts=['authenticate.py'],

    <INSERT_END> <|endoftext|> from setuptools import setup

setup(
    name='bwapi',

    version='3.2.0',

    description='A software development kit for the Brandwatch API',

    url='https://github.com/BrandwatchLtd/api_sdk',

    author='Amy Barker, Jamie Lebovics, Paul Siegel and Jessica Bowden',
    author_email='amyb@brandwatch.com, paul@brandwatch.com, jess@brandwatch.com',

    license='License :: OSI Approved :: MIT License',

    classifiers=[

        'Development Status :: 5 - Production/Stable',

        'Intended Audience :: Developers',

        'License :: OSI Approved :: MIT License',

        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7'
    ],

    py_modules=['bwproject', 'bwresources', 'bwdata', 'filters'],

    scripts=['authenticate.py'],

    install_requires=['requests'],

    tests_require=['responses']

)

Prompt:
Add authenticate.py to installed scripts

from setuptools import setup

setup(
    name='bwapi',

    version='3.2.0',

    description='A software development kit for the Brandwatch API',

    url='https://github.com/BrandwatchLtd/api_sdk',

    author='Amy Barker, Jamie Lebovics, Paul Siegel and Jessica Bowden',
    author_email='amyb@brandwatch.com, paul@brandwatch.com, jess@brandwatch.com',

    license='License :: OSI Approved :: MIT License',

    classifiers=[

        'Development Status :: 5 - Production/Stable',

        'Intended Audience :: Developers',

        'License :: OSI Approved :: MIT License',

        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7'
    ],

    py_modules=['bwproject', 'bwresources', 'bwdata', 'filters'],

    install_requires=['requests'],

    tests_require=['responses']

)


# Generated by Django 3.2.13 on 2022-10-17 13:47

from django.db import migrations

def clear_nlcd2019_gwlfe_results(apps, schema_editor):
    """
    Clear the results for all scenarios belonging to GWLF-E projects made after
    the release of 1.33.0, which had incorrectly aligned NLCD19 2019 on
    2022-01-17:
    https://github.com/WikiWatershed/model-my-watershed/releases/tag/1.33.0

    These results will be recalculated with the correclty aligned NLCD19 values
    when these projects are accessed again.
    """
    Project = apps.get_model('modeling', 'Project')
    Scenario = apps.get_model('modeling', 'Scenario')

    Project.objects.filter(
        model_package='gwlfe',
        created_at__gte='2022-01-17',
    ).update(
        gis_data=None,
        mapshed_job_uuid=None,
        subbasin_mapshed_job_uuid=None,
    )

    Scenario.objects.filter(
        project__model_package='gwlfe',
        project__created_at__gte='2022-01-17',
    ).update(
        results='[]',
        modification_hash='',
    )

class Migration(migrations.Migration):

    dependencies = [
        ('modeling', '0040_clear_nlcd2019_tr55_results'),
    ]

    operations = [
        migrations.RunPython(clear_nlcd2019_gwlfe_results),
    ]

Clear out unaligned NLCD19 GWLF-E results

Adds a migration that clears out all stored results for GWLF-E
projects created on or after 2022-01-17, which is when 1.33.0
was released with incorrectly aligned NLCD19 layers, which had
also been made the default. Thus, every project made after then
had slighly incorrect results.

This migration clears out those bad results. The next time that
project is loaded in the UI, all its results will be recalculated.
This allows us to rebuild the results over time, and not overload
the system all at once.

Response:
<REPLACE_OLD>  <REPLACE_NEW> # Generated by Django 3.2.13 on 2022-10-17 13:47

from django.db import migrations

def clear_nlcd2019_gwlfe_results(apps, schema_editor):
    """
    Clear the results for all scenarios belonging to GWLF-E projects made after
    the release of 1.33.0, which had incorrectly aligned NLCD19 2019 on
    2022-01-17:
    https://github.com/WikiWatershed/model-my-watershed/releases/tag/1.33.0

    These results will be recalculated with the correclty aligned NLCD19 values
    when these projects are accessed again.
    """
    Project = apps.get_model('modeling', 'Project')
    Scenario = apps.get_model('modeling', 'Scenario')

    Project.objects.filter(
        model_package='gwlfe',
        created_at__gte='2022-01-17',
    ).update(
        gis_data=None,
        mapshed_job_uuid=None,
        subbasin_mapshed_job_uuid=None,
    )

    Scenario.objects.filter(
        project__model_package='gwlfe',
        project__created_at__gte='2022-01-17',
    ).update(
        results='[]',
        modification_hash='',
    )

class Migration(migrations.Migration):

    dependencies = [
        ('modeling', '0040_clear_nlcd2019_tr55_results'),
    ]

    operations = [
        migrations.RunPython(clear_nlcd2019_gwlfe_results),
    ]
 <REPLACE_END> <|endoftext|> # Generated by Django 3.2.13 on 2022-10-17 13:47

from django.db import migrations

def clear_nlcd2019_gwlfe_results(apps, schema_editor):
    """
    Clear the results for all scenarios belonging to GWLF-E projects made after
    the release of 1.33.0, which had incorrectly aligned NLCD19 2019 on
    2022-01-17:
    https://github.com/WikiWatershed/model-my-watershed/releases/tag/1.33.0

    These results will be recalculated with the correclty aligned NLCD19 values
    when these projects are accessed again.
    """
    Project = apps.get_model('modeling', 'Project')
    Scenario = apps.get_model('modeling', 'Scenario')

    Project.objects.filter(
        model_package='gwlfe',
        created_at__gte='2022-01-17',
    ).update(
        gis_data=None,
        mapshed_job_uuid=None,
        subbasin_mapshed_job_uuid=None,
    )

    Scenario.objects.filter(
        project__model_package='gwlfe',
        project__created_at__gte='2022-01-17',
    ).update(
        results='[]',
        modification_hash='',
    )

class Migration(migrations.Migration):

    dependencies = [
        ('modeling', '0040_clear_nlcd2019_tr55_results'),
    ]

    operations = [
        migrations.RunPython(clear_nlcd2019_gwlfe_results),
    ]

Prompt:
Clear out unaligned NLCD19 GWLF-E results

Adds a migration that clears out all stored results for GWLF-E
projects created on or after 2022-01-17, which is when 1.33.0
was released with incorrectly aligned NLCD19 layers, which had
also been made the default. Thus, every project made after then
had slighly incorrect results.

This migration clears out those bad results. The next time that
project is loaded in the UI, all its results will be recalculated.
This allows us to rebuild the results over time, and not overload
the system all at once.


#!/usr/bin/env python
# coding=utf-8
'''
This script will help you take out all strings.xml(Placed in a language-region folder) from an Android projectDir
We now use it to provide the strings and upload them to Crowdin.

'''
from os import system,listdir,path
from sys import argv

def takeoutStrings(resPath):
    for item in listdir(resPath):
        itemPath = resPath + '/' + item
        print item
        if (not 'values' in item) :
            rmUnused = 'rm -rf %s'%(itemPath)
            print rmUnused
            system(rmUnused)
            continue

        if ('large' in item or 'dpi' in item):
            rmLayout = 'rm -rf %s'%(itemPath)
            print rmLayout
            system(rmLayout)
            continue

        if (not path.isdir(itemPath)):
            rmFile = 'rm -rf %s'%(itemPath)
            print rmFile
            system(rmFile)
            continue

        for subItem in listdir(itemPath):
            subItemPath = itemPath + '/' + subItem
            if (not 'strings.xml' == subItem):
                rmNotStrings = 'rm -rf %s'%(subItemPath)
                print rmNotStrings
                system(rmNotStrings)

        if (len(listdir(itemPath)) == 0):
            removeEmptyFolder = 'rm -rf %s'%(itemPath)
            print 'Removing empty folder %s'%(itemPath)
            system(removeEmptyFolder)

def main():
    '''
    Usage: takeoutStrings.py projectPath
    '''
    if (len(argv) < 2) :
        print main.__doc__
        return
    projectDir = argv[1]
    projResDir = projectDir + '/res/'
    destBaseDir = '/tmp/'
    destDir = '/tmp/res/'
    cpRes = 'cp %s %s -rf '%(projResDir, destBaseDir)
    print cpRes
    system(cpRes)
    takeoutStrings(destDir)

main()

Add script for Taking out of strings.xml files

Response:
<REPLACE_OLD>  <REPLACE_NEW> #!/usr/bin/env python
# coding=utf-8
'''
This script will help you take out all strings.xml(Placed in a language-region folder) from an Android projectDir
We now use it to provide the strings and upload them to Crowdin.

'''
from os import system,listdir,path
from sys import argv

def takeoutStrings(resPath):
    for item in listdir(resPath):
        itemPath = resPath + '/' + item
        print item
        if (not 'values' in item) :
            rmUnused = 'rm -rf %s'%(itemPath)
            print rmUnused
            system(rmUnused)
            continue

        if ('large' in item or 'dpi' in item):
            rmLayout = 'rm -rf %s'%(itemPath)
            print rmLayout
            system(rmLayout)
            continue

        if (not path.isdir(itemPath)):
            rmFile = 'rm -rf %s'%(itemPath)
            print rmFile
            system(rmFile)
            continue

        for subItem in listdir(itemPath):
            subItemPath = itemPath + '/' + subItem
            if (not 'strings.xml' == subItem):
                rmNotStrings = 'rm -rf %s'%(subItemPath)
                print rmNotStrings
                system(rmNotStrings)

        if (len(listdir(itemPath)) == 0):
            removeEmptyFolder = 'rm -rf %s'%(itemPath)
            print 'Removing empty folder %s'%(itemPath)
            system(removeEmptyFolder)

def main():
    '''
    Usage: takeoutStrings.py projectPath
    '''
    if (len(argv) < 2) :
        print main.__doc__
        return
    projectDir = argv[1]
    projResDir = projectDir + '/res/'
    destBaseDir = '/tmp/'
    destDir = '/tmp/res/'
    cpRes = 'cp %s %s -rf '%(projResDir, destBaseDir)
    print cpRes
    system(cpRes)
    takeoutStrings(destDir)

main()

 <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# coding=utf-8
'''
This script will help you take out all strings.xml(Placed in a language-region folder) from an Android projectDir
We now use it to provide the strings and upload them to Crowdin.

'''
from os import system,listdir,path
from sys import argv

def takeoutStrings(resPath):
    for item in listdir(resPath):
        itemPath = resPath + '/' + item
        print item
        if (not 'values' in item) :
            rmUnused = 'rm -rf %s'%(itemPath)
            print rmUnused
            system(rmUnused)
            continue

        if ('large' in item or 'dpi' in item):
            rmLayout = 'rm -rf %s'%(itemPath)
            print rmLayout
            system(rmLayout)
            continue

        if (not path.isdir(itemPath)):
            rmFile = 'rm -rf %s'%(itemPath)
            print rmFile
            system(rmFile)
            continue

        for subItem in listdir(itemPath):
            subItemPath = itemPath + '/' + subItem
            if (not 'strings.xml' == subItem):
                rmNotStrings = 'rm -rf %s'%(subItemPath)
                print rmNotStrings
                system(rmNotStrings)

        if (len(listdir(itemPath)) == 0):
            removeEmptyFolder = 'rm -rf %s'%(itemPath)
            print 'Removing empty folder %s'%(itemPath)
            system(removeEmptyFolder)

def main():
    '''
    Usage: takeoutStrings.py projectPath
    '''
    if (len(argv) < 2) :
        print main.__doc__
        return
    projectDir = argv[1]
    projResDir = projectDir + '/res/'
    destBaseDir = '/tmp/'
    destDir = '/tmp/res/'
    cpRes = 'cp %s %s -rf '%(projResDir, destBaseDir)
    print cpRes
    system(cpRes)
    takeoutStrings(destDir)

main()

Prompt: Add script for Taking out of strings.xml files


import logging

_log = logging.getLogger(__name__)

def has_permission(request):
    user = getattr(request, 'user', None)
    if user:
        if user.is_superuser:
            return True

        if user.is_staff and user.groups.filter(name__iexact='djedi').exists():
            return True
    else:
        _log.warning("Request does not have `user` attribute. Make sure that "
                     "Djedi middleware is used after AuthenticationMiddleware")

    return False

def get_username(request):
    user = request.user
    if hasattr(user, 'get_username'):
        return user.get_username()
    else:
        return user.username

Handle wrong order of middleware.

Handle wrong order of middleware.

Response:
<REPLACE_OLD> def <REPLACE_NEW> import logging

_log = logging.getLogger(__name__)

def <REPLACE_END> <REPLACE_OLD> request.user
 <REPLACE_NEW> getattr(request, 'user', None)
 <REPLACE_END> <REPLACE_OLD> True

 <REPLACE_NEW> True
    else:
        _log.warning("Request does not have `user` attribute. Make sure that "
                     "Djedi middleware is used after AuthenticationMiddleware")

 <REPLACE_END> <|endoftext|> import logging

_log = logging.getLogger(__name__)

def has_permission(request):
    user = getattr(request, 'user', None)
    if user:
        if user.is_superuser:
            return True

        if user.is_staff and user.groups.filter(name__iexact='djedi').exists():
            return True
    else:
        _log.warning("Request does not have `user` attribute. Make sure that "
                     "Djedi middleware is used after AuthenticationMiddleware")

    return False

def get_username(request):
    user = request.user
    if hasattr(user, 'get_username'):
        return user.get_username()
    else:
        return user.username

Prompt:
Handle wrong order of middleware.

def has_permission(request):
    user = request.user
    if user:
        if user.is_superuser:
            return True

        if user.is_staff and user.groups.filter(name__iexact='djedi').exists():
            return True

    return False

def get_username(request):
    user = request.user
    if hasattr(user, 'get_username'):
        return user.get_username()
    else:
        return user.username


import argparse
import logging

from gensim.models import Word2Vec

logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)

if __name__ == "__main__":
    parser = argparse.ArgumentParser("Convert word2vec model from binary to txt")
    parser.add_argument("model", type=str)
    args = parser.parse_args()

    model = Word2Vec.load_word2vec_format(args.model, binary=True)
    model.save_word2vec_format(args.model + ".txt", binary=False)

    logging.info(model.most_similar(positive=['woman', 'king'], negative=['man']))
    logging.info(model.doesnt_match("breakfast cereal dinner lunch".split()))
    logging.info(model.similarity('woman', 'man'))

Add word2vec binary to txt format converter

Response:
<INSERT> import argparse
import logging

from gensim.models import Word2Vec

logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)

if __name__ == "__main__":
 <INSERT_END> <INSERT>   parser = argparse.ArgumentParser("Convert word2vec model from binary to txt")
    parser.add_argument("model", type=str)
    args = parser.parse_args()

    model = Word2Vec.load_word2vec_format(args.model, binary=True)
    model.save_word2vec_format(args.model + ".txt", binary=False)

    logging.info(model.most_similar(positive=['woman', 'king'], negative=['man']))
    logging.info(model.doesnt_match("breakfast cereal dinner lunch".split()))
    logging.info(model.similarity('woman', 'man'))

 <INSERT_END> <|endoftext|> import argparse
import logging

from gensim.models import Word2Vec

logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)

if __name__ == "__main__":
    parser = argparse.ArgumentParser("Convert word2vec model from binary to txt")
    parser.add_argument("model", type=str)
    args = parser.parse_args()

    model = Word2Vec.load_word2vec_format(args.model, binary=True)
    model.save_word2vec_format(args.model + ".txt", binary=False)

    logging.info(model.most_similar(positive=['woman', 'king'], negative=['man']))
    logging.info(model.doesnt_match("breakfast cereal dinner lunch".split()))
    logging.info(model.similarity('woman', 'man'))

Prompt: Add word2vec binary to txt format converter


import numpy

from chainer import cuda
from chainer import function
from chainer.utils import type_check

class BinaryAccuracy(function.Function):

    ignore_label = -1

    def check_type_forward(self, in_types):
        type_check.expect(in_types.size() == 2)
        x_type, t_type = in_types

        type_check.expect(
            x_type.dtype == numpy.float32,
            t_type.dtype == numpy.int32,
            t_type.shape == x_type.shape,
        )

    def forward(self, inputs):
        xp = cuda.get_array_module(*inputs)
        y, t = inputs
        # flatten
        y = y.ravel()
        t = t.ravel()
        c = (y >= 0)
        count = xp.maximum(1, (t != self.ignore_label).sum())
        return xp.asarray((c == t).sum(dtype='f') / count, dtype='f'),

def binary_accuracy(y, t):
    """Computes binary classification accuracy of the minibatch.

    Args:
        y (Variable): Variable holding a matrix whose i-th element
            indicates the score of positive at the i-th example.
        t (Variable): Variable holding an int32 vector of groundtruth labels.
            If ``t[i] == -1``, correspondig ``x[i]`` is ignored.
            Accuracy is zero if all groundtruth labels are ``-1``.

    Returns:
        Variable: A variable holding a scalar array of the accuracy.

    .. note:: This function is non-differentiable.

    """
    return BinaryAccuracy()(y, t)

Use maximum instead of if-statement

Use maximum instead of if-statement

Response:
<INSERT> xp.maximum(1, <INSERT_END> <REPLACE_OLD> self.ignore_label).sum()
        if int(count) == 0:
            count = 1
 <REPLACE_NEW> self.ignore_label).sum())
 <REPLACE_END> <|endoftext|> import numpy

from chainer import cuda
from chainer import function
from chainer.utils import type_check

class BinaryAccuracy(function.Function):

    ignore_label = -1

    def check_type_forward(self, in_types):
        type_check.expect(in_types.size() == 2)
        x_type, t_type = in_types

        type_check.expect(
            x_type.dtype == numpy.float32,
            t_type.dtype == numpy.int32,
            t_type.shape == x_type.shape,
        )

    def forward(self, inputs):
        xp = cuda.get_array_module(*inputs)
        y, t = inputs
        # flatten
        y = y.ravel()
        t = t.ravel()
        c = (y >= 0)
        count = xp.maximum(1, (t != self.ignore_label).sum())
        return xp.asarray((c == t).sum(dtype='f') / count, dtype='f'),

def binary_accuracy(y, t):
    """Computes binary classification accuracy of the minibatch.

    Args:
        y (Variable): Variable holding a matrix whose i-th element
            indicates the score of positive at the i-th example.
        t (Variable): Variable holding an int32 vector of groundtruth labels.
            If ``t[i] == -1``, correspondig ``x[i]`` is ignored.
            Accuracy is zero if all groundtruth labels are ``-1``.

    Returns:
        Variable: A variable holding a scalar array of the accuracy.

    .. note:: This function is non-differentiable.

    """
    return BinaryAccuracy()(y, t)

Prompt:
Use maximum instead of if-statement

import numpy

from chainer import cuda
from chainer import function
from chainer.utils import type_check

class BinaryAccuracy(function.Function):

    ignore_label = -1

    def check_type_forward(self, in_types):
        type_check.expect(in_types.size() == 2)
        x_type, t_type = in_types

        type_check.expect(
            x_type.dtype == numpy.float32,
            t_type.dtype == numpy.int32,
            t_type.shape == x_type.shape,
        )

    def forward(self, inputs):
        xp = cuda.get_array_module(*inputs)
        y, t = inputs
        # flatten
        y = y.ravel()
        t = t.ravel()
        c = (y >= 0)
        count = (t != self.ignore_label).sum()
        if int(count) == 0:
            count = 1
        return xp.asarray((c == t).sum(dtype='f') / count, dtype='f'),

def binary_accuracy(y, t):
    """Computes binary classification accuracy of the minibatch.

    Args:
        y (Variable): Variable holding a matrix whose i-th element
            indicates the score of positive at the i-th example.
        t (Variable): Variable holding an int32 vector of groundtruth labels.
            If ``t[i] == -1``, correspondig ``x[i]`` is ignored.
            Accuracy is zero if all groundtruth labels are ``-1``.

    Returns:
        Variable: A variable holding a scalar array of the accuracy.

    .. note:: This function is non-differentiable.

    """
    return BinaryAccuracy()(y, t)


from setuptools import setup
import sys

install_requires = [
  'oauth2client>=1.3.2',
  'pyOpenSSL>=0.14',
  'simplejson>=2.3.2',
  ]
tests_require = list(install_requires)

# Python 2 requires Mock to run tests
if sys.version_info < (3, 0):
    tests_require += ['pbr==1.6', 'Mock']

packages = ['identitytoolkit',]

setup(
  name = 'identity-toolkit-python-client',
  packages = packages,
  license="Apache 2.0",
  version = '0.1.7',
  description = 'Google Identity Toolkit python client library',
  author = 'Jin Liu',
  url = 'https://github.com/google/identity-toolkit-python-client',
  download_url = 'https://github.com/google/identity-toolkit-python-client/archive/master.zip',
  keywords = ['identity', 'google', 'login', 'toolkit'], # arbitrary keywords
  classifiers = [
    'Development Status :: 5 - Production/Stable',
    'Intended Audience :: Developers',
    'License :: OSI Approved :: Apache Software License',
    'Operating System :: OS Independent',
    'Programming Language :: Python :: 2.7',
    'Programming Language :: Python :: 3.3',
    'Programming Language :: Python :: 3.4',
    'Topic :: Internet :: WWW/HTTP',
  ],
  install_requires = install_requires,
  tests_require = tests_require,
  test_suite = 'tests',
)

Fix the pyOpenSSL version requirement.

Fix the pyOpenSSL version requirement.

Response:
<REPLACE_OLD> 'pyOpenSSL==0.14',
 <REPLACE_NEW> 'pyOpenSSL>=0.14',
 <REPLACE_END> <|endoftext|> from setuptools import setup
import sys

install_requires = [
  'oauth2client>=1.3.2',
  'pyOpenSSL>=0.14',
  'simplejson>=2.3.2',
  ]
tests_require = list(install_requires)

# Python 2 requires Mock to run tests
if sys.version_info < (3, 0):
    tests_require += ['pbr==1.6', 'Mock']

packages = ['identitytoolkit',]

setup(
  name = 'identity-toolkit-python-client',
  packages = packages,
  license="Apache 2.0",
  version = '0.1.7',
  description = 'Google Identity Toolkit python client library',
  author = 'Jin Liu',
  url = 'https://github.com/google/identity-toolkit-python-client',
  download_url = 'https://github.com/google/identity-toolkit-python-client/archive/master.zip',
  keywords = ['identity', 'google', 'login', 'toolkit'], # arbitrary keywords
  classifiers = [
    'Development Status :: 5 - Production/Stable',
    'Intended Audience :: Developers',
    'License :: OSI Approved :: Apache Software License',
    'Operating System :: OS Independent',
    'Programming Language :: Python :: 2.7',
    'Programming Language :: Python :: 3.3',
    'Programming Language :: Python :: 3.4',
    'Topic :: Internet :: WWW/HTTP',
  ],
  install_requires = install_requires,
  tests_require = tests_require,
  test_suite = 'tests',
)

Prompt:
Fix the pyOpenSSL version requirement.
from setuptools import setup
import sys

install_requires = [
  'oauth2client>=1.3.2',
  'pyOpenSSL==0.14',
  'simplejson>=2.3.2',
  ]
tests_require = list(install_requires)

# Python 2 requires Mock to run tests
if sys.version_info < (3, 0):
    tests_require += ['pbr==1.6', 'Mock']

packages = ['identitytoolkit',]

setup(
  name = 'identity-toolkit-python-client',
  packages = packages,
  license="Apache 2.0",
  version = '0.1.7',
  description = 'Google Identity Toolkit python client library',
  author = 'Jin Liu',
  url = 'https://github.com/google/identity-toolkit-python-client',
  download_url = 'https://github.com/google/identity-toolkit-python-client/archive/master.zip',
  keywords = ['identity', 'google', 'login', 'toolkit'], # arbitrary keywords
  classifiers = [
    'Development Status :: 5 - Production/Stable',
    'Intended Audience :: Developers',
    'License :: OSI Approved :: Apache Software License',
    'Operating System :: OS Independent',
    'Programming Language :: Python :: 2.7',
    'Programming Language :: Python :: 3.3',
    'Programming Language :: Python :: 3.4',
    'Topic :: Internet :: WWW/HTTP',
  ],
  install_requires = install_requires,
  tests_require = tests_require,
  test_suite = 'tests',
)


import sys
from . import layers
from . import utils
from . import nputils
from . import tbutils
from . import distributions
from .utils import FileWriter
from .tbutils import function

if 'ipykernel' in sys.argv[0]:
    from . import nbutils

Add nbutils import to base import

Add nbutils import to base import

Response:
<REPLACE_OLD> from <REPLACE_NEW> import sys
from <REPLACE_END> <REPLACE_OLD> function
 <REPLACE_NEW> function

if 'ipykernel' in sys.argv[0]:
    from . import nbutils
 <REPLACE_END> <|endoftext|> import sys
from . import layers
from . import utils
from . import nputils
from . import tbutils
from . import distributions
from .utils import FileWriter
from .tbutils import function

if 'ipykernel' in sys.argv[0]:
    from . import nbutils

Prompt:
Add nbutils import to base import

from . import layers
from . import utils
from . import nputils
from . import tbutils
from . import distributions
from .utils import FileWriter
from .tbutils import function


#!/bin/env python3
# Prosite regular expressions matcher
# Copyright (c) 2014 Tomasz Truszkowski
# All rights reserved.

import prosite_matcher

if __name__ == '__main__':

	print("\n Hi, this is Prosite Matcher! \n")

	sequence = input("Sequence: ")
	regex = input("Regular expression: ")

	if sequence != None and sequence != "" and regex != None and regex != "":

		prositeMatcher = prosite_matcher.PrositeMatcher()
		prositeMatcher.compile(regex)
		matches, ranges = prositeMatcher.get_matches(sequence)

		print("Found patterns: ", end="")

		if (len(matches) > 0):

			print(sequence[ 0 : ranges[0][0] ], end="")

			for i in range(0, len(matches)):

				print("\033[91m", end="")
				print(sequence[ ranges[i][0] : ranges[i][1] ], end="")
				print("\033[0m", end="")

				if (i < len(matches) - 1):
					print(sequence[ ranges[i][1] : ranges[i + 1][0] ], end="")

			print(sequence[ ranges[len(ranges) - 1][1] : len(sequence)])

		else:

			print(sequence)

		print("")

		for elem in list(zip(matches, ranges)):
			print(elem[0], end=" ")
			print(elem[1])

		print("")

	else:

		print("Sequence and regular expression can't be empty.")

Add check for empty sequence or regex.

Add check for empty sequence or regex.

Response:
<REPLACE_OLD> ")

	prositeMatcher <REPLACE_NEW> ")

	if sequence != None and sequence != "" and regex != None and regex != "":

		prositeMatcher <REPLACE_END> <REPLACE_OLD> prosite_matcher.PrositeMatcher()
	prositeMatcher.compile(regex)
	matches, <REPLACE_NEW> prosite_matcher.PrositeMatcher()
		prositeMatcher.compile(regex)
		matches, <REPLACE_END> <REPLACE_OLD> prositeMatcher.get_matches(sequence)

	print("Found <REPLACE_NEW> prositeMatcher.get_matches(sequence)

		print("Found <REPLACE_END> <REPLACE_OLD> end="")

	if <REPLACE_NEW> end="")

		if <REPLACE_END> <REPLACE_OLD> 0):

		print(sequence[ <REPLACE_NEW> 0):

			print(sequence[ <REPLACE_END> <REPLACE_OLD> end="")

		for <REPLACE_NEW> end="")

			for <REPLACE_END> <REPLACE_OLD> len(matches)):

			print("\033[91m", end="")
			print(sequence[ <REPLACE_NEW> len(matches)):

				print("\033[91m", end="")
				print(sequence[ <REPLACE_END> <REPLACE_OLD> end="")
			print("\033[0m", end="")

			if <REPLACE_NEW> end="")
				print("\033[0m", end="")

				if <REPLACE_END> <REPLACE_OLD> 1):
				print(sequence[ <REPLACE_NEW> 1):
					print(sequence[ <REPLACE_END> <REPLACE_OLD> end="")

		print(sequence[ <REPLACE_NEW> end="")

			print(sequence[ <REPLACE_END> <REPLACE_OLD> len(sequence)])

	else:

		print(sequence)

	print("")

	for <REPLACE_NEW> len(sequence)])

		else:

			print(sequence)

		print("")

		for <REPLACE_END> <REPLACE_OLD> ranges)):
		print(elem[0], <REPLACE_NEW> ranges)):
			print(elem[0], <REPLACE_END> <REPLACE_OLD> ")
		print(elem[1])

	print("")
 <REPLACE_NEW> ")
			print(elem[1])

		print("")

	else:

		print("Sequence and regular expression can't be empty.") <REPLACE_END> <|endoftext|> #!/bin/env python3
# Prosite regular expressions matcher
# Copyright (c) 2014 Tomasz Truszkowski
# All rights reserved.

import prosite_matcher

if __name__ == '__main__':

	print("\n Hi, this is Prosite Matcher! \n")

	sequence = input("Sequence: ")
	regex = input("Regular expression: ")

	if sequence != None and sequence != "" and regex != None and regex != "":

		prositeMatcher = prosite_matcher.PrositeMatcher()
		prositeMatcher.compile(regex)
		matches, ranges = prositeMatcher.get_matches(sequence)

		print("Found patterns: ", end="")

		if (len(matches) > 0):

			print(sequence[ 0 : ranges[0][0] ], end="")

			for i in range(0, len(matches)):

				print("\033[91m", end="")
				print(sequence[ ranges[i][0] : ranges[i][1] ], end="")
				print("\033[0m", end="")

				if (i < len(matches) - 1):
					print(sequence[ ranges[i][1] : ranges[i + 1][0] ], end="")

			print(sequence[ ranges[len(ranges) - 1][1] : len(sequence)])

		else:

			print(sequence)

		print("")

		for elem in list(zip(matches, ranges)):
			print(elem[0], end=" ")
			print(elem[1])

		print("")

	else:

		print("Sequence and regular expression can't be empty.")

Prompt:
Add check for empty sequence or regex.

#!/bin/env python3
# Prosite regular expressions matcher
# Copyright (c) 2014 Tomasz Truszkowski
# All rights reserved.

import prosite_matcher

if __name__ == '__main__':

	print("\n Hi, this is Prosite Matcher! \n")

	sequence = input("Sequence: ")
	regex = input("Regular expression: ")

	prositeMatcher = prosite_matcher.PrositeMatcher()
	prositeMatcher.compile(regex)
	matches, ranges = prositeMatcher.get_matches(sequence)

	print("Found patterns: ", end="")

	if (len(matches) > 0):

		print(sequence[ 0 : ranges[0][0] ], end="")

		for i in range(0, len(matches)):

			print("\033[91m", end="")
			print(sequence[ ranges[i][0] : ranges[i][1] ], end="")
			print("\033[0m", end="")

			if (i < len(matches) - 1):
				print(sequence[ ranges[i][1] : ranges[i + 1][0] ], end="")

		print(sequence[ ranges[len(ranges) - 1][1] : len(sequence)])

	else:

		print(sequence)

	print("")

	for elem in list(zip(matches, ranges)):
		print(elem[0], end=" ")
		print(elem[1])

	print("")


import csv

from money.models import Movement

def parse_csv(raw_csv, parser, header_lines=0, reverse_order=False):
    reader = csv.reader(raw_csv, delimiter=',', quotechar='"')
    rows = []

    for row in reader:
        if reader.line_num > header_lines and row:
            rows.append(parser.parse_row(row))
    if reverse_order:
        rows.reverse()
    return rows

def import_movements(data, bank_account):
    rejected = []
    accepted = 0
    for row in data:
        obj, created = Movement.objects.get_or_create(
            bank_account=bank_account,
            description=row["description"],
            amount=row["amount"],
            date=row["date"],
        )
        if created:
            accepted += 1
        else:
            rejected.append(row)
    return accepted, rejected

Response:
<REPLACE_OLD> header_lines=0):
	reader <REPLACE_NEW> header_lines=0, reverse_order=False):
    reader <REPLACE_END> <REPLACE_OLD> quotechar='"')
	rows = []

	for <REPLACE_NEW> quotechar='"')
    rows = []

    for <REPLACE_END> <REPLACE_OLD> reader:
		if <REPLACE_NEW> reader:
        if <REPLACE_END> <REPLACE_OLD> row:
			rows.append(parser.parse_row(row))
	return <REPLACE_NEW> row:
            rows.append(parser.parse_row(row))
    if reverse_order:
        rows.reverse()
    return <REPLACE_END> <REPLACE_OLD> bank_account):
	rejected = []
	accepted = 0
	for <REPLACE_NEW> bank_account):
    rejected = []
    accepted = 0
    for <REPLACE_END> <REPLACE_OLD> data:
		obj, <REPLACE_NEW> data:
        obj, <REPLACE_END> <REPLACE_OLD> Movement.objects.get_or_create(
			bank_account=bank_account,
			description=row["description"],
			amount=row["amount"],
			date=row["date"],
		)
		if created:
			accepted <REPLACE_NEW> Movement.objects.get_or_create(
            bank_account=bank_account,
            description=row["description"],
            amount=row["amount"],
            date=row["date"],
        )
        if created:
            accepted <REPLACE_END> <REPLACE_OLD> 1
		else:
			rejected.append(row)
	return <REPLACE_NEW> 1
        else:
            rejected.append(row)
    return <REPLACE_END> <REPLACE_OLD> rejected <REPLACE_NEW> rejected
 <REPLACE_END> <|endoftext|> import csv

from money.models import Movement

def parse_csv(raw_csv, parser, header_lines=0, reverse_order=False):
    reader = csv.reader(raw_csv, delimiter=',', quotechar='"')
    rows = []

    for row in reader:
        if reader.line_num > header_lines and row:
            rows.append(parser.parse_row(row))
    if reverse_order:
        rows.reverse()
    return rows

def import_movements(data, bank_account):
    rejected = []
    accepted = 0
    for row in data:
        obj, created = Movement.objects.get_or_create(
            bank_account=bank_account,
            description=row["description"],
            amount=row["amount"],
            date=row["date"],
        )
        if created:
            accepted += 1
        else:
            rejected.append(row)
    return accepted, rejected

Prompt:
Allow to reverse the order of the CSV for a proper reading

import csv

from money.models import Movement

def parse_csv(raw_csv, parser, header_lines=0):
	reader = csv.reader(raw_csv, delimiter=',', quotechar='"')
	rows = []

	for row in reader:
		if reader.line_num > header_lines and row:
			rows.append(parser.parse_row(row))
	return rows

def import_movements(data, bank_account):
	rejected = []
	accepted = 0
	for row in data:
		obj, created = Movement.objects.get_or_create(
			bank_account=bank_account,
			description=row["description"],
			amount=row["amount"],
			date=row["date"],
		)
		if created:
			accepted += 1
		else:
			rejected.append(row)
	return accepted, rejected


# This file is part of h5py, a Python interface to the HDF5 library.
#
# http://www.h5py.org
#
# Copyright 2008-2018 Andrew Collette and contributors
#
# License:  Standard 3-clause BSD; see "license.txt" for full license terms
#           and contributor agreement.

"""
Tests that deprecations work correctly
"""
from __future__ import absolute_import

import h5py
from h5py.h5py_warnings import H5pyDeprecationWarning

from ..common import ut, TestCase

class TestDeprecations(TestCase):
    def test_highlevel_access(self):
        warning_message = (
            "The h5py.highlevel module is deprecated, code should import "
            "directly from h5py, e.g. 'from h5py import File'."
        )
        with self.assertWarnsRegex(H5pyDeprecationWarning, warning_message) as warning:
            File = h5py.highlevel.File

Fix test which appeared to not be run

Response:
<REPLACE_OLD> h5py

from <REPLACE_NEW> h5py
from h5py.h5py_warnings import H5pyDeprecationWarning

from <REPLACE_END> <REPLACE_OLD> hl <REPLACE_NEW> File <REPLACE_END> <REPLACE_OLD> h5py.highlevel
 <REPLACE_NEW> h5py.highlevel.File
 <REPLACE_END> <|endoftext|> # This file is part of h5py, a Python interface to the HDF5 library.
#
# http://www.h5py.org
#
# Copyright 2008-2018 Andrew Collette and contributors
#
# License:  Standard 3-clause BSD; see "license.txt" for full license terms
#           and contributor agreement.

"""
Tests that deprecations work correctly
"""
from __future__ import absolute_import

import h5py
from h5py.h5py_warnings import H5pyDeprecationWarning

from ..common import ut, TestCase

class TestDeprecations(TestCase):
    def test_highlevel_access(self):
        warning_message = (
            "The h5py.highlevel module is deprecated, code should import "
            "directly from h5py, e.g. 'from h5py import File'."
        )
        with self.assertWarnsRegex(H5pyDeprecationWarning, warning_message) as warning:
            File = h5py.highlevel.File

Prompt:
BUG: Fix test which appeared to not be run

# This file is part of h5py, a Python interface to the HDF5 library.
#
# http://www.h5py.org
#
# Copyright 2008-2018 Andrew Collette and contributors
#
# License:  Standard 3-clause BSD; see "license.txt" for full license terms
#           and contributor agreement.

"""
Tests that deprecations work correctly
"""
from __future__ import absolute_import

import h5py

from ..common import ut, TestCase

class TestDeprecations(TestCase):
    def test_highlevel_access(self):
        warning_message = (
            "The h5py.highlevel module is deprecated, code should import "
            "directly from h5py, e.g. 'from h5py import File'."
        )
        with self.assertWarnsRegex(H5pyDeprecationWarning, warning_message) as warning:
            hl = h5py.highlevel


"""Remove mandatory assessment methods from briefs

Revision ID: 630
Revises: 620
Create Date: 2016-06-03 15:26:53.890401

"""

# revision identifiers, used by Alembic.
revision = '630'
down_revision = '620'

from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import table, column
from sqlalchemy.dialects import postgresql

briefs = table(
    'briefs',
    column('id', sa.Integer),
    column('lot_id', sa.Integer),
    column('data', postgresql.JSON),
)

def upgrade():
    conn = op.get_bind()
    for brief in conn.execute(briefs.select()):
        if brief.data.get('evaluationType') is None:
            continue

        optional_methods = list([
            method for method in brief.data['evaluationType']
            if method not in ['Work history', 'Written proposal']
        ])

        if brief.data['evaluationType'] != optional_methods:
            if optional_methods:
                brief.data['evaluationType'] = optional_methods
            else:
                brief.data.pop('evaluationType')

            conn.execute(briefs.update().where(briefs.c.id == brief.id).values(
                data=brief.data
            ))

def downgrade():
    conn = op.get_bind()
    for brief in conn.execute(briefs.select()):
        # Add written proposal to all outcomes and research participants briefs
        if brief.lot_id in [5, 8]:
            brief.data['evaluationType'] = ['Written proposal'] + brief.data.get('evaluationType', [])
        # Add work history to all specialists briefs
        elif brief.lot_id == 6:
            brief.data['evaluationType'] = ['Work history'] + brief.data.get('evaluationType', [])

        conn.execute(briefs.update().where(briefs.c.id == brief.id).values(
            data=brief.data
        ))

Add a migration to drop mandatory assessment methods from brief data

Removes work history and written proposal from all briefs, since
they're no longer a valid option for evaluationType and are added
automatically to all briefs.

Downgrade will add the options to all briefs based on lot. Since we
don't know if the brief had the option selected before the upgrade
migration we add them to ALL briefs, including draft ones. This means
we might end up adding it to briefs that didn't have it before, but
that seems better than silently removing the option, as all briefs
should have them selected in the end.

Response:
<REPLACE_OLD>  <REPLACE_NEW> """Remove mandatory assessment methods from briefs

Revision ID: 630
Revises: 620
Create Date: 2016-06-03 15:26:53.890401

"""

# revision identifiers, used by Alembic.
revision = '630'
down_revision = '620'

from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import table, column
from sqlalchemy.dialects import postgresql

briefs = table(
    'briefs',
    column('id', sa.Integer),
    column('lot_id', sa.Integer),
    column('data', postgresql.JSON),
)

def upgrade():
    conn = op.get_bind()
    for brief in conn.execute(briefs.select()):
        if brief.data.get('evaluationType') is None:
            continue

        optional_methods = list([
            method for method in brief.data['evaluationType']
            if method not in ['Work history', 'Written proposal']
        ])

        if brief.data['evaluationType'] != optional_methods:
            if optional_methods:
                brief.data['evaluationType'] = optional_methods
            else:
                brief.data.pop('evaluationType')

            conn.execute(briefs.update().where(briefs.c.id == brief.id).values(
                data=brief.data
            ))

def downgrade():
    conn = op.get_bind()
    for brief in conn.execute(briefs.select()):
        # Add written proposal to all outcomes and research participants briefs
        if brief.lot_id in [5, 8]:
            brief.data['evaluationType'] = ['Written proposal'] + brief.data.get('evaluationType', [])
        # Add work history to all specialists briefs
        elif brief.lot_id == 6:
            brief.data['evaluationType'] = ['Work history'] + brief.data.get('evaluationType', [])

        conn.execute(briefs.update().where(briefs.c.id == brief.id).values(
            data=brief.data
        ))
 <REPLACE_END> <|endoftext|> """Remove mandatory assessment methods from briefs

Revision ID: 630
Revises: 620
Create Date: 2016-06-03 15:26:53.890401

"""

# revision identifiers, used by Alembic.
revision = '630'
down_revision = '620'

from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import table, column
from sqlalchemy.dialects import postgresql

briefs = table(
    'briefs',
    column('id', sa.Integer),
    column('lot_id', sa.Integer),
    column('data', postgresql.JSON),
)

def upgrade():
    conn = op.get_bind()
    for brief in conn.execute(briefs.select()):
        if brief.data.get('evaluationType') is None:
            continue

        optional_methods = list([
            method for method in brief.data['evaluationType']
            if method not in ['Work history', 'Written proposal']
        ])

        if brief.data['evaluationType'] != optional_methods:
            if optional_methods:
                brief.data['evaluationType'] = optional_methods
            else:
                brief.data.pop('evaluationType')

            conn.execute(briefs.update().where(briefs.c.id == brief.id).values(
                data=brief.data
            ))

def downgrade():
    conn = op.get_bind()
    for brief in conn.execute(briefs.select()):
        # Add written proposal to all outcomes and research participants briefs
        if brief.lot_id in [5, 8]:
            brief.data['evaluationType'] = ['Written proposal'] + brief.data.get('evaluationType', [])
        # Add work history to all specialists briefs
        elif brief.lot_id == 6:
            brief.data['evaluationType'] = ['Work history'] + brief.data.get('evaluationType', [])

        conn.execute(briefs.update().where(briefs.c.id == brief.id).values(
            data=brief.data
        ))

Prompt:
Add a migration to drop mandatory assessment methods from brief data

Removes work history and written proposal from all briefs, since
they're no longer a valid option for evaluationType and are added
automatically to all briefs.

Downgrade will add the options to all briefs based on lot. Since we
don't know if the brief had the option selected before the upgrade
migration we add them to ALL briefs, including draft ones. This means
we might end up adding it to briefs that didn't have it before, but
that seems better than silently removing the option, as all briefs
should have them selected in the end.


import autocomplete_light
from .models import User

class UserAutocomplete(autocomplete_light.AutocompleteModelBase):
    search_fields = ['username']

    def choices_for_request(self, *args, **kwargs):
        qs = super(UserAutocomplete, self).choices_for_request(*args, **kwargs)
        return qs.only('username')
autocomplete_light.register(User, UserAutocomplete)

Fix typo in users autocomplete

Fix typo in users autocomplete

Response:
<REPLACE_OLD> models <REPLACE_NEW> .models <REPLACE_END> <|endoftext|> import autocomplete_light
from .models import User

class UserAutocomplete(autocomplete_light.AutocompleteModelBase):
    search_fields = ['username']

    def choices_for_request(self, *args, **kwargs):
        qs = super(UserAutocomplete, self).choices_for_request(*args, **kwargs)
        return qs.only('username')
autocomplete_light.register(User, UserAutocomplete)

Prompt:
Fix typo in users autocomplete

import autocomplete_light
from models import User

class UserAutocomplete(autocomplete_light.AutocompleteModelBase):
    search_fields = ['username']

    def choices_for_request(self, *args, **kwargs):
        qs = super(UserAutocomplete, self).choices_for_request(*args, **kwargs)
        return qs.only('username')
autocomplete_light.register(User, UserAutocomplete)


#!/usr/bin/env python

# Test for bug reported by Jeremy Hill in which re-opening the screen
# would cause a segfault.

import VisionEgg
VisionEgg.start_default_logging(); VisionEgg.watch_exceptions()

from VisionEgg.Core import Screen, Viewport, swap_buffers
import pygame
from pygame.locals import QUIT,KEYDOWN,MOUSEBUTTONDOWN
from VisionEgg.Text import Text
from VisionEgg.Dots import DotArea2D

def run():
    screen = Screen()
    screen.parameters.bgcolor = (0.0,0.0,0.0) # black (RGB)

    dots = DotArea2D( position                = ( screen.size[0]/2.0, screen.size[1]/2.0 ),
                      size                    = ( 300.0 , 300.0 ),
                      signal_fraction         = 0.1,
                      signal_direction_deg    = 180.0,
                      velocity_pixels_per_sec = 10.0,
                      dot_lifespan_sec        = 5.0,
                      dot_size                = 3.0,
                      num_dots                = 100)

    text = Text( text = "Vision Egg dot_simple_loop demo.",
                 position = (screen.size[0]/2,2),
                 anchor = 'bottom',
                 color = (1.0,1.0,1.0))

    viewport = Viewport( screen=screen, stimuli=[dots,text] )

    # The main loop below is an alternative to using the
    # VisionEgg.FlowControl.Presentation class.

    quit_now = 0
    while not quit_now:
        for event in pygame.event.get():
            if event.type in (QUIT,KEYDOWN,MOUSEBUTTONDOWN):
                quit_now = 1
        screen.clear()
        viewport.draw()
        swap_buffers()
    screen.close()

print "run 1"
run()
print "run 2"
run()
print "done"

Add test script for segfault bug reported by Jeremy Hill.

git-svn-id: 033d166fe8e629f6cbcd3c0e2b9ad0cffc79b88b@1477 3a63a0ee-37fe-0310-a504-e92b6e0a3ba7

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

# Test for bug reported by Jeremy Hill in which re-opening the screen
# would cause a segfault.

import VisionEgg
VisionEgg.start_default_logging(); VisionEgg.watch_exceptions()

from VisionEgg.Core import Screen, Viewport, swap_buffers
import pygame
from pygame.locals import QUIT,KEYDOWN,MOUSEBUTTONDOWN
from VisionEgg.Text import Text
from VisionEgg.Dots import DotArea2D

def run():
    screen = Screen()
    screen.parameters.bgcolor = (0.0,0.0,0.0) # black (RGB)

    dots = DotArea2D( position                = ( screen.size[0]/2.0, screen.size[1]/2.0 ),
                      size                    = ( 300.0 , 300.0 ),
                      signal_fraction         = 0.1,
                      signal_direction_deg    = 180.0,
                      velocity_pixels_per_sec = 10.0,
                      dot_lifespan_sec        = 5.0,
                      dot_size                = 3.0,
                      num_dots                = 100)

    text = Text( text = "Vision Egg dot_simple_loop demo.",
                 position = (screen.size[0]/2,2),
                 anchor = 'bottom',
                 color = (1.0,1.0,1.0))

    viewport = Viewport( screen=screen, stimuli=[dots,text] )

    # The main loop below is an alternative to using the
    # VisionEgg.FlowControl.Presentation class.

    quit_now = 0
    while not quit_now:
        for event in pygame.event.get():
            if event.type in (QUIT,KEYDOWN,MOUSEBUTTONDOWN):
                quit_now = 1
        screen.clear()
        viewport.draw()
        swap_buffers()
    screen.close()

print "run 1"
run()
print "run 2"
run()
print "done"
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

# Test for bug reported by Jeremy Hill in which re-opening the screen
# would cause a segfault.

import VisionEgg
VisionEgg.start_default_logging(); VisionEgg.watch_exceptions()

from VisionEgg.Core import Screen, Viewport, swap_buffers
import pygame
from pygame.locals import QUIT,KEYDOWN,MOUSEBUTTONDOWN
from VisionEgg.Text import Text
from VisionEgg.Dots import DotArea2D

def run():
    screen = Screen()
    screen.parameters.bgcolor = (0.0,0.0,0.0) # black (RGB)

    dots = DotArea2D( position                = ( screen.size[0]/2.0, screen.size[1]/2.0 ),
                      size                    = ( 300.0 , 300.0 ),
                      signal_fraction         = 0.1,
                      signal_direction_deg    = 180.0,
                      velocity_pixels_per_sec = 10.0,
                      dot_lifespan_sec        = 5.0,
                      dot_size                = 3.0,
                      num_dots                = 100)

    text = Text( text = "Vision Egg dot_simple_loop demo.",
                 position = (screen.size[0]/2,2),
                 anchor = 'bottom',
                 color = (1.0,1.0,1.0))

    viewport = Viewport( screen=screen, stimuli=[dots,text] )

    # The main loop below is an alternative to using the
    # VisionEgg.FlowControl.Presentation class.

    quit_now = 0
    while not quit_now:
        for event in pygame.event.get():
            if event.type in (QUIT,KEYDOWN,MOUSEBUTTONDOWN):
                quit_now = 1
        screen.clear()
        viewport.draw()
        swap_buffers()
    screen.close()

print "run 1"
run()
print "run 2"
run()
print "done"

Prompt:
Add test script for segfault bug reported by Jeremy Hill.

git-svn-id: 033d166fe8e629f6cbcd3c0e2b9ad0cffc79b88b@1477 3a63a0ee-37fe-0310-a504-e92b6e0a3ba7


# -*- coding: UTF-8 -*-
"""
before_step(context, step), after_step(context, step)
    These run before and after every step.
    The step passed in is an instance of Step.

before_scenario(context, scenario), after_scenario(context, scenario)
    These run before and after each scenario is run.
    The scenario passed in is an instance of Scenario.

before_feature(context, feature), after_feature(context, feature)
    These run before and after each feature file is exercised.
    The feature passed in is an instance of Feature.

before_tag(context, tag), after_tag(context, tag)

"""

import logging
import os.path
import shutil

def before_all(context):
    if not context.config.log_capture:
        logging.basicConfig(level=logging.DEBUG)

def after_all(context):
    # TEMPORARILY-DISABLED: print "SUMMARY:"
    pass

#def before_feature(context, feature):
#    context.workdir = None
#
#def after_feature(context, feature):
#    # destroy_workdir(context.workdir)
#    context.workdir = None
#
#def destroy_workdir(workdir):
#    if workdir and os.path.exists(workdir):
#        shutil.rmtree(workdir, ignore_errors=True)

Disable after_all() output for now.

Disable after_all() output for now.

Response:
<INSERT> # TEMPORARILY-DISABLED: <INSERT_END> <REPLACE_OLD> "SUMMARY:"

#def <REPLACE_NEW> "SUMMARY:"
    pass

#def <REPLACE_END> <|endoftext|> # -*- coding: UTF-8 -*-
"""
before_step(context, step), after_step(context, step)
    These run before and after every step.
    The step passed in is an instance of Step.

before_scenario(context, scenario), after_scenario(context, scenario)
    These run before and after each scenario is run.
    The scenario passed in is an instance of Scenario.

before_feature(context, feature), after_feature(context, feature)
    These run before and after each feature file is exercised.
    The feature passed in is an instance of Feature.

before_tag(context, tag), after_tag(context, tag)

"""

import logging
import os.path
import shutil

def before_all(context):
    if not context.config.log_capture:
        logging.basicConfig(level=logging.DEBUG)

def after_all(context):
    # TEMPORARILY-DISABLED: print "SUMMARY:"
    pass

#def before_feature(context, feature):
#    context.workdir = None
#
#def after_feature(context, feature):
#    # destroy_workdir(context.workdir)
#    context.workdir = None
#
#def destroy_workdir(workdir):
#    if workdir and os.path.exists(workdir):
#        shutil.rmtree(workdir, ignore_errors=True)

Prompt:
Disable after_all() output for now.

# -*- coding: UTF-8 -*-
"""
before_step(context, step), after_step(context, step)
    These run before and after every step.
    The step passed in is an instance of Step.

before_scenario(context, scenario), after_scenario(context, scenario)
    These run before and after each scenario is run.
    The scenario passed in is an instance of Scenario.

before_feature(context, feature), after_feature(context, feature)
    These run before and after each feature file is exercised.
    The feature passed in is an instance of Feature.

before_tag(context, tag), after_tag(context, tag)

"""

import logging
import os.path
import shutil

def before_all(context):
    if not context.config.log_capture:
        logging.basicConfig(level=logging.DEBUG)

def after_all(context):
    print "SUMMARY:"

#def before_feature(context, feature):
#    context.workdir = None
#
#def after_feature(context, feature):
#    # destroy_workdir(context.workdir)
#    context.workdir = None
#
#def destroy_workdir(workdir):
#    if workdir and os.path.exists(workdir):
#        shutil.rmtree(workdir, ignore_errors=True)


from olcc.models import ImportRecord

"""
Inject the last import date into the request context.
"""
def last_updated(request):
    try:
        return {
            'last_updated': ImportRecord.objects.latest().created_at
        }
    except ImportRecord.DoesNotExist:
        pass

Response:
<REPLACE_OLD> record = ImportRecord.objects.latest()
    if record:
 <REPLACE_NEW> try:
 <REPLACE_END> <REPLACE_OLD> record.created_at
 <REPLACE_NEW> ImportRecord.objects.latest().created_at
 <REPLACE_END> <INSERT>    except ImportRecord.DoesNotExist:
        pass
 <INSERT_END> <|endoftext|> from olcc.models import ImportRecord

"""
Inject the last import date into the request context.
"""
def last_updated(request):
    try:
        return {
            'last_updated': ImportRecord.objects.latest().created_at
        }
    except ImportRecord.DoesNotExist:
        pass

Prompt:
Fix a DoesNotExist bug in the olcc context processor.

from olcc.models import ImportRecord

"""
Inject the last import date into the request context.
"""
def last_updated(request):
    record = ImportRecord.objects.latest()
    if record:
        return {
            'last_updated': record.created_at
        }


from celery.task import task
from make_mozilla.bsd import BSDRegisterConstituent

@task
def register_email_address_as_constituent(email_address, group):
    BSDRegisterConstituent.add_email_to_group(email_address, group)

Response:
<REPLACE_OLD> celery.decorators <REPLACE_NEW> celery.task <REPLACE_END> <|endoftext|> from celery.task import task
from make_mozilla.bsd import BSDRegisterConstituent

@task
def register_email_address_as_constituent(email_address, group):
    BSDRegisterConstituent.add_email_to_group(email_address, group)

Prompt:
Switch to post Celery 2.2 task decorator syntax.
from celery.decorators import task
from make_mozilla.bsd import BSDRegisterConstituent

@task
def register_email_address_as_constituent(email_address, group):
    BSDRegisterConstituent.add_email_to_group(email_address, group)


#!/bin/env python
"""Run HTCondor-CE unit tests"""

import glob
import unittest
import sys

TESTS = [test.strip('.py') for test in glob.glob('test*.py')]
SUITE = unittest.TestLoader().loadTestsFromNames(TESTS)
RESULTS = unittest.TextTestRunner(verbosity=2).run(SUITE)

if not RESULTS.wasSuccessful():
    sys.exit(1)

Exit non-zero if unit tests failed

Exit non-zero if unit tests failed

Response:
<REPLACE_OLD> unittest

TESTS <REPLACE_NEW> unittest
import sys

TESTS <REPLACE_END> <REPLACE_OLD> unittest.TestLoader().loadTestsFromNames(TESTS)
unittest.TextTestRunner(verbosity=2).run(SUITE)

 <REPLACE_NEW> unittest.TestLoader().loadTestsFromNames(TESTS)
RESULTS = unittest.TextTestRunner(verbosity=2).run(SUITE)

if not RESULTS.wasSuccessful():
    sys.exit(1)

 <REPLACE_END> <|endoftext|> #!/bin/env python
"""Run HTCondor-CE unit tests"""

import glob
import unittest
import sys

TESTS = [test.strip('.py') for test in glob.glob('test*.py')]
SUITE = unittest.TestLoader().loadTestsFromNames(TESTS)
RESULTS = unittest.TextTestRunner(verbosity=2).run(SUITE)

if not RESULTS.wasSuccessful():
    sys.exit(1)

Prompt:
Exit non-zero if unit tests failed

#!/bin/env python
"""Run HTCondor-CE unit tests"""

import glob
import unittest

TESTS = [test.strip('.py') for test in glob.glob('test*.py')]
SUITE = unittest.TestLoader().loadTestsFromNames(TESTS)
unittest.TextTestRunner(verbosity=2).run(SUITE)


from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements

class LimitMode(ModuleData, Mode):
    implements(IPlugin, IModuleData, IMode)

    name = "LimitMode"
    core = True
    affectedActions = [ "joinpermission" ]

    def hookIRCd(self, ircd):
        self.ircd = ircd

    def channelModes(self):
        return [ ("l", ModeType.Param, self) ]

    def actions(self):
        return [ ("modeactioncheck-channel-l-joinpermission", 10, self.isModeSet) ]

    def isModeSet(self, channel, alsoChannel, user):
        if "l" in channel.modes:
            return channel.modes["l"]
        return None

    def checkSet(self, channel, param):
        if param.isdigit():
            return [param]
        return None

    def apply(self, actionType, channel, param, alsoChannel, user):
        try: # There may be cases when the parameter we're passed is in string form still (e.g. from modules other than this one)
            param = int(param)
        except ValueError:
            return None
        if len(channel.users) >= param:
            user.sendMessage(irc.ERR_CHANNELISFULL, channel.name, ":Cannot join channel (Channel is full)")
            return False
        return None

limitMode = LimitMode()

Response:
<REPLACE_OLD> param
 <REPLACE_NEW> [param]
 <REPLACE_END> <|endoftext|> from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements

class LimitMode(ModuleData, Mode):
    implements(IPlugin, IModuleData, IMode)

    name = "LimitMode"
    core = True
    affectedActions = [ "joinpermission" ]

    def hookIRCd(self, ircd):
        self.ircd = ircd

    def channelModes(self):
        return [ ("l", ModeType.Param, self) ]

    def actions(self):
        return [ ("modeactioncheck-channel-l-joinpermission", 10, self.isModeSet) ]

    def isModeSet(self, channel, alsoChannel, user):
        if "l" in channel.modes:
            return channel.modes["l"]
        return None

    def checkSet(self, channel, param):
        if param.isdigit():
            return [param]
        return None

    def apply(self, actionType, channel, param, alsoChannel, user):
        try: # There may be cases when the parameter we're passed is in string form still (e.g. from modules other than this one)
            param = int(param)
        except ValueError:
            return None
        if len(channel.users) >= param:
            user.sendMessage(irc.ERR_CHANNELISFULL, channel.name, ":Cannot join channel (Channel is full)")
            return False
        return None

limitMode = LimitMode()

Prompt:
Return the parameter for channel mode +l as a list

This fixes a bug where every digit was handled as a separate parameter, causing
"MODE #channel +l 10" to turn into "MODE #channel +ll 1 0"

from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements

class LimitMode(ModuleData, Mode):
    implements(IPlugin, IModuleData, IMode)

    name = "LimitMode"
    core = True
    affectedActions = [ "joinpermission" ]

    def hookIRCd(self, ircd):
        self.ircd = ircd

    def channelModes(self):
        return [ ("l", ModeType.Param, self) ]

    def actions(self):
        return [ ("modeactioncheck-channel-l-joinpermission", 10, self.isModeSet) ]

    def isModeSet(self, channel, alsoChannel, user):
        if "l" in channel.modes:
            return channel.modes["l"]
        return None

    def checkSet(self, channel, param):
        if param.isdigit():
            return param
        return None

    def apply(self, actionType, channel, param, alsoChannel, user):
        try: # There may be cases when the parameter we're passed is in string form still (e.g. from modules other than this one)
            param = int(param)
        except ValueError:
            return None
        if len(channel.users) >= param:
            user.sendMessage(irc.ERR_CHANNELISFULL, channel.name, ":Cannot join channel (Channel is full)")
            return False
        return None

limitMode = LimitMode()


# Generated by statirator
import os

# directories setup

ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
SOURCE_DIR = os.path.join(ROOT_DIR, '{{ source }}')
BUILD_DIR = os.path.join(ROOT_DIR, '{{ build }}')

# languages setup

LANGUAGE_CODE = '{{default_lang}}'
_ = lambda s:s

LANGUAGES = ({% for code, name in languages %}
    ('{{code}}', _('{{ name }}')),
{% endfor %})

ROOT_URLCONF = '{{ project_name }}.urls'

TEMPLATE_DIRS = (
    os.path.join(ROOT_DIR, 'templates'),
)

INSTALLED_APPS = (
    'django.contrib.contenttypes',
    'django.contrib.sites',
    'django.contrib.staticfiles',
    'django_medusa',
    'taggit',
    'statirator.blog',
)

MEDUSA_RENDERER_CLASS = "django_medusa.renderers.DiskStaticSiteRenderer"
MEDUSA_MULTITHREAD = True
MEDUSA_DEPLOY_DIR = BUILD_DIR

Response:
<REPLACE_OLD> 'django_medusa',
)

MEDUSA_RENDERER_CLASS <REPLACE_NEW> 'django_medusa',
    'taggit',
    'statirator.blog',
)

MEDUSA_RENDERER_CLASS <REPLACE_END> <|endoftext|> # Generated by statirator
import os

# directories setup

ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
SOURCE_DIR = os.path.join(ROOT_DIR, '{{ source }}')
BUILD_DIR = os.path.join(ROOT_DIR, '{{ build }}')

# languages setup

LANGUAGE_CODE = '{{default_lang}}'
_ = lambda s:s

LANGUAGES = ({% for code, name in languages %}
    ('{{code}}', _('{{ name }}')),
{% endfor %})

ROOT_URLCONF = '{{ project_name }}.urls'

TEMPLATE_DIRS = (
    os.path.join(ROOT_DIR, 'templates'),
)

INSTALLED_APPS = (
    'django.contrib.contenttypes',
    'django.contrib.sites',
    'django.contrib.staticfiles',
    'django_medusa',
    'taggit',
    'statirator.blog',
)

MEDUSA_RENDERER_CLASS = "django_medusa.renderers.DiskStaticSiteRenderer"
MEDUSA_MULTITHREAD = True
MEDUSA_DEPLOY_DIR = BUILD_DIR

Prompt:
Add taggit and statirator.blog to INSTALLED_APPS

# Generated by statirator
import os

# directories setup

ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
SOURCE_DIR = os.path.join(ROOT_DIR, '{{ source }}')
BUILD_DIR = os.path.join(ROOT_DIR, '{{ build }}')

# languages setup

LANGUAGE_CODE = '{{default_lang}}'
_ = lambda s:s

LANGUAGES = ({% for code, name in languages %}
    ('{{code}}', _('{{ name }}')),
{% endfor %})

ROOT_URLCONF = '{{ project_name }}.urls'

TEMPLATE_DIRS = (
    os.path.join(ROOT_DIR, 'templates'),
)

INSTALLED_APPS = (
    'django.contrib.contenttypes',
    'django.contrib.sites',
    'django.contrib.staticfiles',
    'django_medusa',
)

MEDUSA_RENDERER_CLASS = "django_medusa.renderers.DiskStaticSiteRenderer"
MEDUSA_MULTITHREAD = True
MEDUSA_DEPLOY_DIR = BUILD_DIR


"""
Page navigation groups allow assigning pages to differing navigation lists
such as header, footer and what else.
"""

from __future__ import absolute_import, unicode_literals

from django.db import models
from django.utils.translation import ugettext_lazy as _

from feincms import extensions

class Extension(extensions.Extension):
    ident = 'navigationgroups'
    groups = [
        ('default', _('Default')),
        ('footer', _('Footer')),
    ]

    def handle_model(self):
        self.model.add_to_class(
            'navigation_group',
            models.CharField(
                _('navigation group'),
                choices=self.groups,
                default=self.groups[0][0],
                max_length=20,
                blank=True,
                db_index=True))

    def handle_modeladmin(self, modeladmin):
        modeladmin.add_extension_options('navigation_group')
        modeladmin.extend_list('list_display', ['navigation_group'])
        modeladmin.extend_list('list_filter', ['navigation_group'])

Allow navigationgroup to be blank

Allow navigationgroup to be blank

Response:
<INSERT> blank=True,
                <INSERT_END> <|endoftext|> """
Page navigation groups allow assigning pages to differing navigation lists
such as header, footer and what else.
"""

from __future__ import absolute_import, unicode_literals

from django.db import models
from django.utils.translation import ugettext_lazy as _

from feincms import extensions

class Extension(extensions.Extension):
    ident = 'navigationgroups'
    groups = [
        ('default', _('Default')),
        ('footer', _('Footer')),
    ]

    def handle_model(self):
        self.model.add_to_class(
            'navigation_group',
            models.CharField(
                _('navigation group'),
                choices=self.groups,
                default=self.groups[0][0],
                max_length=20,
                blank=True,
                db_index=True))

    def handle_modeladmin(self, modeladmin):
        modeladmin.add_extension_options('navigation_group')
        modeladmin.extend_list('list_display', ['navigation_group'])
        modeladmin.extend_list('list_filter', ['navigation_group'])

Prompt:
Allow navigationgroup to be blank

"""
Page navigation groups allow assigning pages to differing navigation lists
such as header, footer and what else.
"""

from __future__ import absolute_import, unicode_literals

from django.db import models
from django.utils.translation import ugettext_lazy as _

from feincms import extensions

class Extension(extensions.Extension):
    ident = 'navigationgroups'
    groups = [
        ('default', _('Default')),
        ('footer', _('Footer')),
    ]

    def handle_model(self):
        self.model.add_to_class(
            'navigation_group',
            models.CharField(
                _('navigation group'),
                choices=self.groups,
                default=self.groups[0][0],
                max_length=20,
                db_index=True))

    def handle_modeladmin(self, modeladmin):
        modeladmin.add_extension_options('navigation_group')
        modeladmin.extend_list('list_display', ['navigation_group'])
        modeladmin.extend_list('list_filter', ['navigation_group'])


"""Manual test for figure.show() in the inline matplotlib backend.

This script should be loaded for interactive use (via %load) into a qtconsole
or notebook initialized with the pylab inline backend.

Expected behavior: only *one* copy of the figure is shown.

For further details:
https://github.com/ipython/ipython/issues/1612
https://github.com/matplotlib/matplotlib/issues/835
"""

import numpy as np
import matplotlib.pyplot as plt

plt.ioff()
x = np.random.uniform(-5, 5, size=(100))
y = np.random.uniform(-5, 5, size=(100))
f = plt.figure()
plt.scatter(x, y)
plt.plot(y)
f.show()

Add manual test file as per review by @minrk.

Response:
<INSERT> """Manual test for figure.show() in the inline matplotlib backend.

This script should be loaded for interactive use (via %load) into a qtconsole
or notebook initialized with the pylab inline backend. <INSERT_END> <INSERT>

Expected behavior: only *one* copy of the figure is shown.

For further details:
https://github.com/ipython/ipython/issues/1612
https://github.com/matplotlib/matplotlib/issues/835
"""

import numpy as np
import matplotlib.pyplot as plt

plt.ioff()
x = np.random.uniform(-5, 5, size=(100))
y = np.random.uniform(-5, 5, size=(100))
f = plt.figure()
plt.scatter(x, y)
plt.plot(y)
f.show()
 <INSERT_END> <|endoftext|> """Manual test for figure.show() in the inline matplotlib backend.

This script should be loaded for interactive use (via %load) into a qtconsole
or notebook initialized with the pylab inline backend.

Expected behavior: only *one* copy of the figure is shown.

For further details:
https://github.com/ipython/ipython/issues/1612
https://github.com/matplotlib/matplotlib/issues/835
"""

import numpy as np
import matplotlib.pyplot as plt

plt.ioff()
x = np.random.uniform(-5, 5, size=(100))
y = np.random.uniform(-5, 5, size=(100))
f = plt.figure()
plt.scatter(x, y)
plt.plot(y)
f.show()

Prompt: Add manual test file as per review by @minrk.


# Copyright 2019 Komit <https://komit-consulting.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).

import logging
from odoo import api, models, _
from odoo.exceptions import UserError

_logger = logging.getLogger(__name__)

try:
    from validate_email import validate_email
except ImportError:
    _logger.debug('Cannot import "validate_email".')

    def validate_email(email):
        _logger.warning(
            'Can not validate email, '
            'python dependency required "validate_email"')
        return True

class ResPartner(models.Model):
    _inherit = 'res.partner'

    @api.constrains('email')
    def constrains_email(self):
        for rec in self.filtered("email"):
            self.email_check(rec.email)

    @api.model
    def email_check(self, email):
        if validate_email(email):
            return True
        raise UserError(_('Invalid e-mail!'))

Response:
<REPLACE_OLD> _logger.error('Cannot <REPLACE_NEW> _logger.debug('Cannot <REPLACE_END> <|endoftext|> # Copyright 2019 Komit <https://komit-consulting.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).

import logging
from odoo import api, models, _
from odoo.exceptions import UserError

_logger = logging.getLogger(__name__)

try:
    from validate_email import validate_email
except ImportError:
    _logger.debug('Cannot import "validate_email".')

    def validate_email(email):
        _logger.warning(
            'Can not validate email, '
            'python dependency required "validate_email"')
        return True

class ResPartner(models.Model):
    _inherit = 'res.partner'

    @api.constrains('email')
    def constrains_email(self):
        for rec in self.filtered("email"):
            self.email_check(rec.email)

    @api.model
    def email_check(self, email):
        if validate_email(email):
            return True
        raise UserError(_('Invalid e-mail!'))

Prompt:
 [FIX][11.0] Make debugger record a debug message instead of error when importing validate_email in partner_email_check

# Copyright 2019 Komit <https://komit-consulting.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).

import logging
from odoo import api, models, _
from odoo.exceptions import UserError

_logger = logging.getLogger(__name__)

try:
    from validate_email import validate_email
except ImportError:
    _logger.error('Cannot import "validate_email".')

    def validate_email(email):
        _logger.warning(
            'Can not validate email, '
            'python dependency required "validate_email"')
        return True

class ResPartner(models.Model):
    _inherit = 'res.partner'

    @api.constrains('email')
    def constrains_email(self):
        for rec in self.filtered("email"):
            self.email_check(rec.email)

    @api.model
    def email_check(self, email):
        if validate_email(email):
            return True
        raise UserError(_('Invalid e-mail!'))


from ometa.interp import TrampolinedGrammarInterpreter, _feed_me

class TrampolinedParser:
    """
    A parser that incrementally parses incoming data.
    """
    def __init__(self, grammar, receiver, bindings):
        """
        Initializes the parser.

        @param grammar: The grammar used to parse the incoming data.
        @param receiver: Responsible for logic operation on the parsed data.
            Typically, the logic operation will be invoked inside the grammar,
            e.g., rule = expr1 expr2 (-> receiver.doSomeStuff())
        @param bindings: The namespace that can be accessed inside the grammar.
        """
        self.grammar = grammar
        self.bindings = dict(bindings)
        self.bindings['receiver'] = self.receiver = receiver
        self._setupInterp()

    def _setupInterp(self):
        """
        Resets the parser. The parser will begin parsing with the rule named
        'initial'.
        """
        self._interp = TrampolinedGrammarInterpreter(
            grammar=self.grammar, ruleName=self.receiver.currentRule,
            callback=None, globals=self.bindings)

    def receive(self, data):
        """
        Receive the incoming data and begin parsing. The parser will parse the
        data incrementally according to the 'initial' rule in the grammar.

        @param data: The raw data received.
        """
        while data:
            status = self._interp.receive(data)
            if status is _feed_me:
                return
            data = ''.join(self._interp.input.data[self._interp.input.position:])
            self._setupInterp()

Response:
<REPLACE_OLD> ruleName='initial', callback=None,
            <REPLACE_NEW> ruleName=self.receiver.currentRule,
            callback=None, <REPLACE_END> <DELETE> try:
                <DELETE_END> <DELETE>            except Exception as e:
                # maybe we should raise it?
                raise e
            else:
     <DELETE_END> <DELETE>     <DELETE_END> <REPLACE_OLD> self._setupInterp() <REPLACE_NEW> self._setupInterp()
 <REPLACE_END> <|endoftext|> from ometa.interp import TrampolinedGrammarInterpreter, _feed_me

class TrampolinedParser:
    """
    A parser that incrementally parses incoming data.
    """
    def __init__(self, grammar, receiver, bindings):
        """
        Initializes the parser.

        @param grammar: The grammar used to parse the incoming data.
        @param receiver: Responsible for logic operation on the parsed data.
            Typically, the logic operation will be invoked inside the grammar,
            e.g., rule = expr1 expr2 (-> receiver.doSomeStuff())
        @param bindings: The namespace that can be accessed inside the grammar.
        """
        self.grammar = grammar
        self.bindings = dict(bindings)
        self.bindings['receiver'] = self.receiver = receiver
        self._setupInterp()

    def _setupInterp(self):
        """
        Resets the parser. The parser will begin parsing with the rule named
        'initial'.
        """
        self._interp = TrampolinedGrammarInterpreter(
            grammar=self.grammar, ruleName=self.receiver.currentRule,
            callback=None, globals=self.bindings)

    def receive(self, data):
        """
        Receive the incoming data and begin parsing. The parser will parse the
        data incrementally according to the 'initial' rule in the grammar.

        @param data: The raw data received.
        """
        while data:
            status = self._interp.receive(data)
            if status is _feed_me:
                return
            data = ''.join(self._interp.input.data[self._interp.input.position:])
            self._setupInterp()

Prompt:
Update TrampolinedParser a little for my purposes.

from ometa.interp import TrampolinedGrammarInterpreter, _feed_me

class TrampolinedParser:
    """
    A parser that incrementally parses incoming data.
    """
    def __init__(self, grammar, receiver, bindings):
        """
        Initializes the parser.

        @param grammar: The grammar used to parse the incoming data.
        @param receiver: Responsible for logic operation on the parsed data.
            Typically, the logic operation will be invoked inside the grammar,
            e.g., rule = expr1 expr2 (-> receiver.doSomeStuff())
        @param bindings: The namespace that can be accessed inside the grammar.
        """
        self.grammar = grammar
        self.bindings = dict(bindings)
        self.bindings['receiver'] = self.receiver = receiver
        self._setupInterp()

    def _setupInterp(self):
        """
        Resets the parser. The parser will begin parsing with the rule named
        'initial'.
        """
        self._interp = TrampolinedGrammarInterpreter(
            grammar=self.grammar, ruleName='initial', callback=None,
            globals=self.bindings)

    def receive(self, data):
        """
        Receive the incoming data and begin parsing. The parser will parse the
        data incrementally according to the 'initial' rule in the grammar.

        @param data: The raw data received.
        """
        while data:
            try:
                status = self._interp.receive(data)
            except Exception as e:
                # maybe we should raise it?
                raise e
            else:
                if status is _feed_me:
                    return
            data = ''.join(self._interp.input.data[self._interp.input.position:])
            self._setupInterp()


from itertools import chain
from rest_framework import permissions
from datetime import datetime
from seven23 import settings

class CanWriteAccount(permissions.BasePermission):
    """
        Object-level permission to only allow owners of an object to edit it.
        Assumes the model instance has an `owner` attribute.
    """

    def has_object_permission(self, request, view, obj):
        # Read permissions are allowed to any request,
        # so we'll always allow GET, HEAD or OPTIONS requests.
        # Instance must have an attribute named `owner`.
        return obj.account.id in list(chain(
            request.user.accounts.values_list('id', flat=True),
            request.user.guests.values_list('account__id', flat=True)
        ))

class IsPaid(permissions.BasePermission):
    """
        Check if user has a paid formula
    """

    def has_permission(self, request, view):
        # Read permissions are allowed to any request,
        # so we'll always allow GET, HEAD or OPTIONS requests.

        if not settings.SAAS:
            return True

        if request.method in permissions.SAFE_METHODS:
            return True

        return request.user.profile.valid_until > datetime.today()

Response:
<REPLACE_OLD> django.utils import timezone
from <REPLACE_NEW> datetime import datetime
from <REPLACE_END> <REPLACE_OLD> timezone.now() <REPLACE_NEW> datetime.today() <REPLACE_END> <|endoftext|>
from itertools import chain
from rest_framework import permissions
from datetime import datetime
from seven23 import settings

class CanWriteAccount(permissions.BasePermission):
    """
        Object-level permission to only allow owners of an object to edit it.
        Assumes the model instance has an `owner` attribute.
    """

    def has_object_permission(self, request, view, obj):
        # Read permissions are allowed to any request,
        # so we'll always allow GET, HEAD or OPTIONS requests.
        # Instance must have an attribute named `owner`.
        return obj.account.id in list(chain(
            request.user.accounts.values_list('id', flat=True),
            request.user.guests.values_list('account__id', flat=True)
        ))

class IsPaid(permissions.BasePermission):
    """
        Check if user has a paid formula
    """

    def has_permission(self, request, view):
        # Read permissions are allowed to any request,
        # so we'll always allow GET, HEAD or OPTIONS requests.

        if not settings.SAAS:
            return True

        if request.method in permissions.SAFE_METHODS:
            return True

        return request.user.profile.valid_until > datetime.today()

Prompt:
Fix issue with imezone on IsPaid Permission

from itertools import chain
from rest_framework import permissions
from django.utils import timezone
from seven23 import settings

class CanWriteAccount(permissions.BasePermission):
    """
        Object-level permission to only allow owners of an object to edit it.
        Assumes the model instance has an `owner` attribute.
    """

    def has_object_permission(self, request, view, obj):
        # Read permissions are allowed to any request,
        # so we'll always allow GET, HEAD or OPTIONS requests.
        # Instance must have an attribute named `owner`.
        return obj.account.id in list(chain(
            request.user.accounts.values_list('id', flat=True),
            request.user.guests.values_list('account__id', flat=True)
        ))

class IsPaid(permissions.BasePermission):
    """
        Check if user has a paid formula
    """

    def has_permission(self, request, view):
        # Read permissions are allowed to any request,
        # so we'll always allow GET, HEAD or OPTIONS requests.

        if not settings.SAAS:
            return True

        if request.method in permissions.SAFE_METHODS:
            return True

        return request.user.profile.valid_until > timezone.now()