Add script's path to the python path

Add script's path to the python path

--- leisure/__init__.py
+++ leisure/__init__.py
@@ -27,6 +27,7 @@

 from __future__ import absolute_import
 import sys
+import os

 from .disco import run_script
 from . import shuffle
@@ -35,6 +36,10 @@

 def main():
   script = sys.argv[1]
+  script_dir = os.path.abspath(os.path.dirname(script))
+  if script_dir not in [os.path.abspath(p) for p in sys.path]:
+    sys.path.append(script_dir)
+
   if len(sys.argv) == 3:
     data_root = sys.argv[2]
   else:

<|original_code|>
# -*- coding: utf-8 -*-
"""
    leisure
    ~~~~~~~~

    Leisure a local job runner for Disco based project.

    It provides a useful method for running your disco project without
    needing a full disco cluster.  This makes it a snap to develop and
    debug jobs on your development machine.

    To use, simply execute your disco script using the leisure
    command like so:

      $ leisure <path to script>/word_count.py

    Leisure monkey patches all network calls to the Disco/DDFS master
    so that it can intercept and execute them locally. The
    worker itself is executed as a subprocess and communicated to via
    the Disco Worker protocol
    http://discoproject.org/doc/disco/howto/worker.html

    :copyright: (c) 2011 by triv.io, see AUTHORS for more details.
    :license: MIT, see LICENSE for more details.
"""

from __future__ import absolute_import
import sys

from .disco import run_script
from . import shuffle

import tempfile

def main():
  script = sys.argv[1]
  if len(sys.argv) == 3:
    data_root = sys.argv[2]
  else:
    data_root = tempfile.mkdtemp()
  run_script(script, data_root)

if __name__ == "__main__":
  main()

<|edits_diff|>
--- leisure/__init__.py
+++ leisure/__init__.py
@@ -27,6 +27,7 @@

 from __future__ import absolute_import
 import sys
+import os

 from .disco import run_script
 from . import shuffle
<|current_version|>
# -*- coding: utf-8 -*-
"""
    leisure
    ~~~~~~~~

    Leisure a local job runner for Disco based project.

    It provides a useful method for running your disco project without
    needing a full disco cluster.  This makes it a snap to develop and
    debug jobs on your development machine.

    To use, simply execute your disco script using the leisure
    command like so:

      $ leisure <path to script>/word_count.py

    Leisure monkey patches all network calls to the Disco/DDFS master
    so that it can intercept and execute them locally. The
    worker itself is executed as a subprocess and communicated to via
    the Disco Worker protocol
    http://discoproject.org/doc/disco/howto/worker.html

    :copyright: (c) 2011 by triv.io, see AUTHORS for more details.
    :license: MIT, see LICENSE for more details.
"""

from __future__ import absolute_import
import sys
import os

from .disco import run_script
from . import shuffle

import tempfile

def main():
  script = sys.argv[1]
  if len(sys.argv) == 3:
    data_root = sys.argv[2]
  else:
    data_root = tempfile.mkdtemp()
  run_script(script, data_root)

if __name__ == "__main__":
  main()

<|next_version|>
# -*- coding: utf-8 -*-
"""
    leisure
    ~~~~~~~~

    Leisure a local job runner for Disco based project.

    It provides a useful method for running your disco project without
    needing a full disco cluster.  This makes it a snap to develop and
    debug jobs on your development machine.

    To use, simply execute your disco script using the leisure
    command like so:

      $ leisure <path to script>/word_count.py

    Leisure monkey patches all network calls to the Disco/DDFS master
    so that it can intercept and execute them locally. The
    worker itself is executed as a subprocess and communicated to via
    the Disco Worker protocol
    http://discoproject.org/doc/disco/howto/worker.html

    :copyright: (c) 2011 by triv.io, see AUTHORS for more details.
    :license: MIT, see LICENSE for more details.
"""

from __future__ import absolute_import
import sys
import os

from .disco import run_script
from . import shuffle

import tempfile

def main():
  script = sys.argv[1]
  script_dir = os.path.abspath(os.path.dirname(script))
  if script_dir not in [os.path.abspath(p) for p in sys.path]:
    sys.path.append(script_dir)

  if len(sys.argv) == 3:
    data_root = sys.argv[2]
  else:
    data_root = tempfile.mkdtemp()
  run_script(script, data_root)

if __name__ == "__main__":
  main()


Add call to get the database size, as JSON

--- server.py
+++ server.py
@@ -1,4 +1,5 @@
 import argparse
+import json

 from flask import Flask, request

@@ -7,7 +8,14 @@
                     help="enable Flask debug mode. DO NOT use in production.")
 args = parser.parse_args()

+NUM_RECORDS = 5
+RECORD_SIZE = 64
+
 app = Flask(__name__)
+
+@app.route('/db_size')
+def get_db_size():
+    return json.dumps({'num_records': NUM_RECORDS, 'record_size': RECORD_SIZE})

 @app.route('/retrieve', methods=['POST'])
 def get():

<|original_code|>
import argparse

from flask import Flask, request

parser = argparse.ArgumentParser(description="Start a Blindstore server.")
parser.add_argument('-d', '--debug', action='store_true',
                    help="enable Flask debug mode. DO NOT use in production.")
args = parser.parse_args()

app = Flask(__name__)

@app.route('/retrieve', methods=['POST'])
def get():
    public_key = request.form['PUBLIC_KEY']
    enc_index  = request.form['ENC_INDEX']

    return "/retrieve index '{index}' with key '{key}'".format(index=enc_index, key=public_key)

@app.route('/set', methods=['POST'])
def put():
    enc_index = request.form['ENC_INDEX']
    enc_data  = request.form['ENC_DATA']

    return "/set '{index}' to '{data}'".format(data=enc_data, index=enc_index)

if __name__ == '__main__':
    app.run(debug=args.debug)

<|edits_diff|>
--- server.py
+++ server.py
@@ -1,4 +1,5 @@
 import argparse
+import json

 from flask import Flask, request

@@ -6,6 +7,9 @@
 parser.add_argument('-d', '--debug', action='store_true',
                     help="enable Flask debug mode. DO NOT use in production.")
 args = parser.parse_args()
+
+NUM_RECORDS = 5
+RECORD_SIZE = 64

 app = Flask(__name__)

<|current_version|>
import argparse
import json

from flask import Flask, request

parser = argparse.ArgumentParser(description="Start a Blindstore server.")
parser.add_argument('-d', '--debug', action='store_true',
                    help="enable Flask debug mode. DO NOT use in production.")
args = parser.parse_args()

NUM_RECORDS = 5
RECORD_SIZE = 64

app = Flask(__name__)

@app.route('/retrieve', methods=['POST'])
def get():
    public_key = request.form['PUBLIC_KEY']
    enc_index  = request.form['ENC_INDEX']

    return "/retrieve index '{index}' with key '{key}'".format(index=enc_index, key=public_key)

@app.route('/set', methods=['POST'])
def put():
    enc_index = request.form['ENC_INDEX']
    enc_data  = request.form['ENC_DATA']

    return "/set '{index}' to '{data}'".format(data=enc_data, index=enc_index)

if __name__ == '__main__':
    app.run(debug=args.debug)

<|next_version|>
import argparse
import json

from flask import Flask, request

parser = argparse.ArgumentParser(description="Start a Blindstore server.")
parser.add_argument('-d', '--debug', action='store_true',
                    help="enable Flask debug mode. DO NOT use in production.")
args = parser.parse_args()

NUM_RECORDS = 5
RECORD_SIZE = 64

app = Flask(__name__)

@app.route('/db_size')
def get_db_size():
    return json.dumps({'num_records': NUM_RECORDS, 'record_size': RECORD_SIZE})

@app.route('/retrieve', methods=['POST'])
def get():
    public_key = request.form['PUBLIC_KEY']
    enc_index  = request.form['ENC_INDEX']

    return "/retrieve index '{index}' with key '{key}'".format(index=enc_index, key=public_key)

@app.route('/set', methods=['POST'])
def put():
    enc_index = request.form['ENC_INDEX']
    enc_data  = request.form['ENC_DATA']

    return "/set '{index}' to '{data}'".format(data=enc_data, index=enc_index)

if __name__ == '__main__':
    app.run(debug=args.debug)


Revert "Fix a codacy issue"

Revert "Fix a codacy issue"

This reverts commit 0fe83f1bfa54eda16c42fb5d81b33215dc3ba562.

--- tests/test_emailharvesterws.py
+++ tests/test_emailharvesterws.py
@@ -8,9 +8,12 @@
 Tests for `botanick` module.
 """

+import pytest
+

 from botanick import Botanick

 def test_botanick():
 	emails_found = Botanick.search("squad.pro")
 	assert emails_found != ""
+	print(emails_found)

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

"""
test_botanick
----------------------------------

Tests for `botanick` module.
"""

from botanick import Botanick

def test_botanick():
	emails_found = Botanick.search("squad.pro")
	assert emails_found != ""

<|edits_diff|>
--- tests/test_emailharvesterws.py
+++ tests/test_emailharvesterws.py
@@ -8,6 +8,8 @@
 Tests for `botanick` module.
 """

+import pytest
+

 from botanick import Botanick

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

"""
test_botanick
----------------------------------

Tests for `botanick` module.
"""

import pytest

from botanick import Botanick

def test_botanick():
	emails_found = Botanick.search("squad.pro")
	assert emails_found != ""

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

"""
test_botanick
----------------------------------

Tests for `botanick` module.
"""

import pytest

from botanick import Botanick

def test_botanick():
	emails_found = Botanick.search("squad.pro")
	assert emails_found != ""
	print(emails_found)


Add --dev command line arg

Add --dev command line arg

--- virtool/app_init.py
+++ virtool/app_init.py
@@ -29,8 +29,11 @@
     )

     parser.add_argument(
+        "--dev",
+        dest="dev",
         action="store_true",
         default=False,
+        help="run in dev mode"
     )

     parser.add_argument(

<|original_code|>
import coloredlogs
import logging.handlers

from argparse import ArgumentParser

def get_args():

    parser = ArgumentParser()

    parser.add_argument(
        "-H", "--host",
        dest="host",
        help="hostname to listen on"
    )

    parser.add_argument(
        "-p", "--port",
        dest="port",
        help="port to listen on"
    )

    parser.add_argument(
        "-v", "--verbose",
        dest="verbose",
        action="store_true",
        default=False,
        help="log debug messages"
    )

    parser.add_argument(
        action="store_true",
        default=False,
    )

    parser.add_argument(
        "--force-version",
        dest="force_version",
        help="make the server think it is the passed FORCE_VERSION or v1.8.5 if none provided",
        nargs="?",
        const="v1.8.5"
    )

    return parser.parse_args()

def configure(verbose=False):
    logging_level = logging.INFO if verbose else logging.DEBUG

    logging.captureWarnings(True)

    log_format = "%(asctime)-20s %(module)-11s %(levelname)-8s %(message)s"

    coloredlogs.install(
        level=logging_level,
        fmt=log_format
    )

    logger = logging.getLogger("virtool")

    handler = logging.handlers.RotatingFileHandler("virtool.log", maxBytes=1000000, backupCount=5)
    handler.setFormatter(logging.Formatter(log_format))

    logger.addHandler(handler)

    return logger

<|edits_diff|>
--- virtool/app_init.py
+++ virtool/app_init.py
@@ -29,6 +29,8 @@
     )

     parser.add_argument(
+        "--dev",
+        dest="dev",
         action="store_true",
         default=False,
     )
<|current_version|>
import coloredlogs
import logging.handlers

from argparse import ArgumentParser

def get_args():

    parser = ArgumentParser()

    parser.add_argument(
        "-H", "--host",
        dest="host",
        help="hostname to listen on"
    )

    parser.add_argument(
        "-p", "--port",
        dest="port",
        help="port to listen on"
    )

    parser.add_argument(
        "-v", "--verbose",
        dest="verbose",
        action="store_true",
        default=False,
        help="log debug messages"
    )

    parser.add_argument(
        "--dev",
        dest="dev",
        action="store_true",
        default=False,
    )

    parser.add_argument(
        "--force-version",
        dest="force_version",
        help="make the server think it is the passed FORCE_VERSION or v1.8.5 if none provided",
        nargs="?",
        const="v1.8.5"
    )

    return parser.parse_args()

def configure(verbose=False):
    logging_level = logging.INFO if verbose else logging.DEBUG

    logging.captureWarnings(True)

    log_format = "%(asctime)-20s %(module)-11s %(levelname)-8s %(message)s"

    coloredlogs.install(
        level=logging_level,
        fmt=log_format
    )

    logger = logging.getLogger("virtool")

    handler = logging.handlers.RotatingFileHandler("virtool.log", maxBytes=1000000, backupCount=5)
    handler.setFormatter(logging.Formatter(log_format))

    logger.addHandler(handler)

    return logger

<|next_version|>
import coloredlogs
import logging.handlers

from argparse import ArgumentParser

def get_args():

    parser = ArgumentParser()

    parser.add_argument(
        "-H", "--host",
        dest="host",
        help="hostname to listen on"
    )

    parser.add_argument(
        "-p", "--port",
        dest="port",
        help="port to listen on"
    )

    parser.add_argument(
        "-v", "--verbose",
        dest="verbose",
        action="store_true",
        default=False,
        help="log debug messages"
    )

    parser.add_argument(
        "--dev",
        dest="dev",
        action="store_true",
        default=False,
        help="run in dev mode"
    )

    parser.add_argument(
        "--force-version",
        dest="force_version",
        help="make the server think it is the passed FORCE_VERSION or v1.8.5 if none provided",
        nargs="?",
        const="v1.8.5"
    )

    return parser.parse_args()

def configure(verbose=False):
    logging_level = logging.INFO if verbose else logging.DEBUG

    logging.captureWarnings(True)

    log_format = "%(asctime)-20s %(module)-11s %(levelname)-8s %(message)s"

    coloredlogs.install(
        level=logging_level,
        fmt=log_format
    )

    logger = logging.getLogger("virtool")

    handler = logging.handlers.RotatingFileHandler("virtool.log", maxBytes=1000000, backupCount=5)
    handler.setFormatter(logging.Formatter(log_format))

    logger.addHandler(handler)

    return logger


Update quickstart project to use AUTO_*

Update quickstart project to use AUTO_*

--- streamparse/bootstrap/project/src/bolts/wordcount.py
+++ streamparse/bootstrap/project/src/bolts/wordcount.py
@@ -3,7 +3,12 @@
 from collections import Counter
 from streamparse.bolt import Bolt

+
 class WordCounter(Bolt):
+
+    AUTO_ACK = True  # automatically acknowledge tuples after process()
+    AUTO_ANCHOR = True  # automatically anchor tuples to current tuple
+    AUTO_FAIL = True  # automatically fail tuples when exceptions occur

     def initialize(self, conf, ctx):
         self.counts = Counter()

<|original_code|>
from __future__ import absolute_import, print_function, unicode_literals

from collections import Counter
from streamparse.bolt import Bolt

class WordCounter(Bolt):

    def initialize(self, conf, ctx):
        self.counts = Counter()

    def process(self, tup):
        word = tup.values[0]
        self.counts[word] += 1
        self.emit([word, self.counts[word]])
        self.log('%s: %d' % (word, self.counts[word]))

<|edits_diff|>
--- streamparse/bootstrap/project/src/bolts/wordcount.py
+++ streamparse/bootstrap/project/src/bolts/wordcount.py
@@ -2,6 +2,7 @@

 from collections import Counter
 from streamparse.bolt import Bolt
+

 class WordCounter(Bolt):

<|current_version|>
from __future__ import absolute_import, print_function, unicode_literals

from collections import Counter
from streamparse.bolt import Bolt

class WordCounter(Bolt):

    def initialize(self, conf, ctx):
        self.counts = Counter()

    def process(self, tup):
        word = tup.values[0]
        self.counts[word] += 1
        self.emit([word, self.counts[word]])
        self.log('%s: %d' % (word, self.counts[word]))

<|next_version|>
from __future__ import absolute_import, print_function, unicode_literals

from collections import Counter
from streamparse.bolt import Bolt

class WordCounter(Bolt):

    AUTO_ACK = True  # automatically acknowledge tuples after process()
    AUTO_ANCHOR = True  # automatically anchor tuples to current tuple
    AUTO_FAIL = True  # automatically fail tuples when exceptions occur

    def initialize(self, conf, ctx):
        self.counts = Counter()

    def process(self, tup):
        word = tup.values[0]
        self.counts[word] += 1
        self.emit([word, self.counts[word]])
        self.log('%s: %d' % (word, self.counts[word]))


Make official google imports actually work.

--- core/__init__.py
+++ core/__init__.py
@@ -1,10 +1,13 @@
 # Offer forward compatible imports of datastore_rpc and datastore_query.

 import logging
+import sys

 try:
   from google.appengine.datastore import datastore_rpc
   from google.appengine.datastore import datastore_query
+  sys.modules['core.datastore_rpc'] = datastore_rpc
+  sys.modules['core.datastore_query'] = datastore_query
   logging.info('Imported official google datastore_{rpc,query}')
 except ImportError:
   logging.warning('Importing local datastore_{rpc,query}')

<|original_code|>
# Offer forward compatible imports of datastore_rpc and datastore_query.

import logging

try:
  from google.appengine.datastore import datastore_rpc
  from google.appengine.datastore import datastore_query
  logging.info('Imported official google datastore_{rpc,query}')
except ImportError:
  logging.warning('Importing local datastore_{rpc,query}')
  from . import datastore_rpc
  from . import datastore_query
  from . import monkey

<|edits_diff|>
--- core/__init__.py
+++ core/__init__.py
@@ -1,6 +1,7 @@
 # Offer forward compatible imports of datastore_rpc and datastore_query.

 import logging
+import sys

 try:
   from google.appengine.datastore import datastore_rpc
<|current_version|>
# Offer forward compatible imports of datastore_rpc and datastore_query.

import logging
import sys

try:
  from google.appengine.datastore import datastore_rpc
  from google.appengine.datastore import datastore_query
  logging.info('Imported official google datastore_{rpc,query}')
except ImportError:
  logging.warning('Importing local datastore_{rpc,query}')
  from . import datastore_rpc
  from . import datastore_query
  from . import monkey

<|next_version|>
# Offer forward compatible imports of datastore_rpc and datastore_query.

import logging
import sys

try:
  from google.appengine.datastore import datastore_rpc
  from google.appengine.datastore import datastore_query
  sys.modules['core.datastore_rpc'] = datastore_rpc
  sys.modules['core.datastore_query'] = datastore_query
  logging.info('Imported official google datastore_{rpc,query}')
except ImportError:
  logging.warning('Importing local datastore_{rpc,query}')
  from . import datastore_rpc
  from . import datastore_query
  from . import monkey


Add workaround for Travis CI problems

Add workaround for Travis CI problems

--- tests/functional/subcommands/test_subcommands.py
+++ tests/functional/subcommands/test_subcommands.py
@@ -1,4 +1,10 @@
+import sys
+import pytest
 import subprocess
+
+
+if (3, 6) <= sys.version_info < (3, 8):
+    pytest.skip("Temporary workaround for Travis problems", allow_module_level=True)

 def test_subcommand():

<|original_code|>
import subprocess

def test_subcommand():
    """
    Test that a command from the example project is registered.
    """
    output = subprocess.check_output(['textx'], stderr=subprocess.STDOUT)
    assert b'testcommand' in output

def test_subcommand_group():
    """
    Test that a command group is registered.
    """
    output = subprocess.check_output(['textx', 'testgroup'],
                                     stderr=subprocess.STDOUT)
    assert b'groupcommand1' in output
    assert b'groupcommand2' in output

<|edits_diff|>
--- tests/functional/subcommands/test_subcommands.py
+++ tests/functional/subcommands/test_subcommands.py
@@ -1,3 +1,5 @@
+import sys
+import pytest
 import subprocess

<|current_version|>
import sys
import pytest
import subprocess

def test_subcommand():
    """
    Test that a command from the example project is registered.
    """
    output = subprocess.check_output(['textx'], stderr=subprocess.STDOUT)
    assert b'testcommand' in output

def test_subcommand_group():
    """
    Test that a command group is registered.
    """
    output = subprocess.check_output(['textx', 'testgroup'],
                                     stderr=subprocess.STDOUT)
    assert b'groupcommand1' in output
    assert b'groupcommand2' in output

<|next_version|>
import sys
import pytest
import subprocess

if (3, 6) <= sys.version_info < (3, 8):
    pytest.skip("Temporary workaround for Travis problems", allow_module_level=True)

def test_subcommand():
    """
    Test that a command from the example project is registered.
    """
    output = subprocess.check_output(['textx'], stderr=subprocess.STDOUT)
    assert b'testcommand' in output

def test_subcommand_group():
    """
    Test that a command group is registered.
    """
    output = subprocess.check_output(['textx', 'testgroup'],
                                     stderr=subprocess.STDOUT)
    assert b'groupcommand1' in output
    assert b'groupcommand2' in output


Add reference to user model and __unicode__() method to FacebookProfileModel

--- django_facebook/models.py
+++ django_facebook/models.py
@@ -1,4 +1,5 @@
 from django.db import models
+from django.contrib.auth.models import User

 class FacebookProfileModel(models.Model):
     '''
@@ -7,6 +8,7 @@
     NOTE: If you don't use this this abstract class, make sure you copy/paste
     the fields in.
     '''
+    user = models.OneToOneField(User)
     about_me = models.TextField(blank=True, null=True)
     facebook_id = models.IntegerField(blank=True, null=True)
     facebook_name = models.CharField(max_length=255, blank=True, null=True)
@@ -15,6 +17,9 @@
     blog_url = models.TextField(blank=True, null=True)
     image = models.ImageField(blank=True, null=True, upload_to='profile_images')
     date_of_birth = models.DateField(blank=True, null=True)
+
+    def __unicode__(self):
+       return self.user.__unicode__()

     class Meta:
         abstract = True

<|original_code|>
from django.db import models

class FacebookProfileModel(models.Model):
    '''
    Abstract class to add to your profile model.

    NOTE: If you don't use this this abstract class, make sure you copy/paste
    the fields in.
    '''
    about_me = models.TextField(blank=True, null=True)
    facebook_id = models.IntegerField(blank=True, null=True)
    facebook_name = models.CharField(max_length=255, blank=True, null=True)
    facebook_profile_url = models.TextField(blank=True, null=True)
    website_url = models.TextField(blank=True, null=True)
    blog_url = models.TextField(blank=True, null=True)
    image = models.ImageField(blank=True, null=True, upload_to='profile_images')
    date_of_birth = models.DateField(blank=True, null=True)

    class Meta:
        abstract = True
<|edits_diff|>
--- django_facebook/models.py
+++ django_facebook/models.py
@@ -1,4 +1,5 @@
 from django.db import models
+from django.contrib.auth.models import User

 class FacebookProfileModel(models.Model):
     '''
@@ -7,6 +8,7 @@
     NOTE: If you don't use this this abstract class, make sure you copy/paste
     the fields in.
     '''
+    user = models.OneToOneField(User)
     about_me = models.TextField(blank=True, null=True)
     facebook_id = models.IntegerField(blank=True, null=True)
     facebook_name = models.CharField(max_length=255, blank=True, null=True)
<|current_version|>
from django.db import models
from django.contrib.auth.models import User

class FacebookProfileModel(models.Model):
    '''
    Abstract class to add to your profile model.

    NOTE: If you don't use this this abstract class, make sure you copy/paste
    the fields in.
    '''
    user = models.OneToOneField(User)
    about_me = models.TextField(blank=True, null=True)
    facebook_id = models.IntegerField(blank=True, null=True)
    facebook_name = models.CharField(max_length=255, blank=True, null=True)
    facebook_profile_url = models.TextField(blank=True, null=True)
    website_url = models.TextField(blank=True, null=True)
    blog_url = models.TextField(blank=True, null=True)
    image = models.ImageField(blank=True, null=True, upload_to='profile_images')
    date_of_birth = models.DateField(blank=True, null=True)

    class Meta:
        abstract = True

<|next_version|>
from django.db import models
from django.contrib.auth.models import User

class FacebookProfileModel(models.Model):
    '''
    Abstract class to add to your profile model.

    NOTE: If you don't use this this abstract class, make sure you copy/paste
    the fields in.
    '''
    user = models.OneToOneField(User)
    about_me = models.TextField(blank=True, null=True)
    facebook_id = models.IntegerField(blank=True, null=True)
    facebook_name = models.CharField(max_length=255, blank=True, null=True)
    facebook_profile_url = models.TextField(blank=True, null=True)
    website_url = models.TextField(blank=True, null=True)
    blog_url = models.TextField(blank=True, null=True)
    image = models.ImageField(blank=True, null=True, upload_to='profile_images')
    date_of_birth = models.DateField(blank=True, null=True)

    def __unicode__(self):
       return self.user.__unicode__()

    class Meta:
        abstract = True


Patch parameter --prefix does need a path seperator

The --prefix parameter of the patch command needs a path seperator at
the end to store the backup in a directory.

--- quilt/patch.py
+++ quilt/patch.py
@@ -19,6 +19,8 @@
 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 # 02110-1301 USA

+import os
+
 from quilt.utils import Process

 class Patch(object):
@@ -29,6 +31,8 @@
             cmd.append("--backup")
         if prefix:
             cmd.append("--prefix")
+            if not prefix[-1] == os.sep:
+                prefix += os.sep
             cmd.append(prefix)
         cmd.append("-i")
         cmd.append(patch_file)

<|original_code|>
# vim: fileencoding=utf-8 et sw=4 ts=4 tw=80:

# python-quilt - A Python implementation of the quilt patch system
#
# Copyright (C) 2012  Björn Ricks <bjoern.ricks@googlemail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.

# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.

# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA

from quilt.utils import Process

class Patch(object):

    def __init__(self, cwd, patch_file, backup=False, prefix=None):
        cmd = ["patch"]
        if backup:
            cmd.append("--backup")
        if prefix:
            cmd.append("--prefix")
            cmd.append(prefix)
        cmd.append("-i")
        cmd.append(patch_file)

        Process(cmd).run(cwd=cwd)

<|edits_diff|>
--- quilt/patch.py
+++ quilt/patch.py
@@ -19,6 +19,8 @@
 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 # 02110-1301 USA

+import os
+
 from quilt.utils import Process

 class Patch(object):
<|current_version|>
# vim: fileencoding=utf-8 et sw=4 ts=4 tw=80:

# python-quilt - A Python implementation of the quilt patch system
#
# Copyright (C) 2012  Björn Ricks <bjoern.ricks@googlemail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.

# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.

# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA

import os

from quilt.utils import Process

class Patch(object):

    def __init__(self, cwd, patch_file, backup=False, prefix=None):
        cmd = ["patch"]
        if backup:
            cmd.append("--backup")
        if prefix:
            cmd.append("--prefix")
            cmd.append(prefix)
        cmd.append("-i")
        cmd.append(patch_file)

        Process(cmd).run(cwd=cwd)

<|next_version|>
# vim: fileencoding=utf-8 et sw=4 ts=4 tw=80:

# python-quilt - A Python implementation of the quilt patch system
#
# Copyright (C) 2012  Björn Ricks <bjoern.ricks@googlemail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.

# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.

# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA

import os

from quilt.utils import Process

class Patch(object):

    def __init__(self, cwd, patch_file, backup=False, prefix=None):
        cmd = ["patch"]
        if backup:
            cmd.append("--backup")
        if prefix:
            cmd.append("--prefix")
            if not prefix[-1] == os.sep:
                prefix += os.sep
            cmd.append(prefix)
        cmd.append("-i")
        cmd.append(patch_file)

        Process(cmd).run(cwd=cwd)


Make sure current date is late enough

Make sure current date is late enough

--- integration_tests/tests/hello_world_sleep_and_time.py
+++ integration_tests/tests/hello_world_sleep_and_time.py
@@ -3,6 +3,7 @@
 timeout = 2

 SLEEP_INTERVAL = int(100e6)
+MIN_TIME = 1451606400000000000 # 2016-1-1 0:0:0.0 UTC

 def check_state(state):
     import re
@@ -22,4 +23,5 @@
     for t in times:
         diff = t - prev
         assert diff >= SLEEP_INTERVAL, "Sleep interval must be >= {0}".format(SLEEP_INTERVAL)
+        assert t >= MIN_TIME, "Time must be after {0}".format(MIN_TIME)
         prev = diff

<|original_code|>
integration_test = True

timeout = 2

SLEEP_INTERVAL = int(100e6)

def check_state(state):
    import re
    from functools import partial
    from operator import is_not

    r = re.compile('^(\d+) \[.*\] Hello World!')
    lines = map(r.match, state.console.split('\n'))
    lines = filter(partial(is_not, None), lines)
    times = map(lambda m: int(m.group(1)), lines)
    times = list(times)

    min_times = (timeout - 1) * int(1e9) // SLEEP_INTERVAL
    assert len(times) >= min_times, "Expected at least {0} hello worlds".format(min_times)

    prev = 0
    for t in times:
        diff = t - prev
        assert diff >= SLEEP_INTERVAL, "Sleep interval must be >= {0}".format(SLEEP_INTERVAL)
        prev = diff

<|edits_diff|>
--- integration_tests/tests/hello_world_sleep_and_time.py
+++ integration_tests/tests/hello_world_sleep_and_time.py
@@ -3,6 +3,7 @@
 timeout = 2

 SLEEP_INTERVAL = int(100e6)
+MIN_TIME = 1451606400000000000 # 2016-1-1 0:0:0.0 UTC

 def check_state(state):
     import re
<|current_version|>
integration_test = True

timeout = 2

SLEEP_INTERVAL = int(100e6)
MIN_TIME = 1451606400000000000 # 2016-1-1 0:0:0.0 UTC

def check_state(state):
    import re
    from functools import partial
    from operator import is_not

    r = re.compile('^(\d+) \[.*\] Hello World!')
    lines = map(r.match, state.console.split('\n'))
    lines = filter(partial(is_not, None), lines)
    times = map(lambda m: int(m.group(1)), lines)
    times = list(times)

    min_times = (timeout - 1) * int(1e9) // SLEEP_INTERVAL
    assert len(times) >= min_times, "Expected at least {0} hello worlds".format(min_times)

    prev = 0
    for t in times:
        diff = t - prev
        assert diff >= SLEEP_INTERVAL, "Sleep interval must be >= {0}".format(SLEEP_INTERVAL)
        prev = diff

<|next_version|>
integration_test = True

timeout = 2

SLEEP_INTERVAL = int(100e6)
MIN_TIME = 1451606400000000000 # 2016-1-1 0:0:0.0 UTC

def check_state(state):
    import re
    from functools import partial
    from operator import is_not

    r = re.compile('^(\d+) \[.*\] Hello World!')
    lines = map(r.match, state.console.split('\n'))
    lines = filter(partial(is_not, None), lines)
    times = map(lambda m: int(m.group(1)), lines)
    times = list(times)

    min_times = (timeout - 1) * int(1e9) // SLEEP_INTERVAL
    assert len(times) >= min_times, "Expected at least {0} hello worlds".format(min_times)

    prev = 0
    for t in times:
        diff = t - prev
        assert diff >= SLEEP_INTERVAL, "Sleep interval must be >= {0}".format(SLEEP_INTERVAL)
        assert t >= MIN_TIME, "Time must be after {0}".format(MIN_TIME)
        prev = diff


Throw on invalid / missing credentials.

Throw on invalid / missing credentials.

--- packs/travisci/actions/lib/action.py
+++ packs/travisci/actions/lib/action.py
@@ -1,3 +1,5 @@
+import httplib
+
 import requests

 from st2actions.runners.pythonrunner import Action
@@ -30,4 +32,9 @@
             headers = self._get_auth_headers()
             response = requests.put(url, data=data, headers=headers)

+        if response.status_code in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
+            msg = ('Invalid or missing Travis CI auth token. Make sure you have'
+                   'specified valid token in the config file')
+            raise Exception(msg)
+
         return response

<|original_code|>
import requests

from st2actions.runners.pythonrunner import Action

API_URL = 'https://api.travis-ci.org'
HEADERS_ACCEPT = 'application/vnd.travis-ci.2+json'
CONTENT_TYPE = 'application/json'

class TravisCI(Action):
    def _get_auth_headers(self):
        headers = {}
        headers['Authorization'] = self.config['Authorization']
        headers['Content-Type'] = self.config['Content-Type']
        return headers

    def _perform_request(self, path, method, data=None, requires_auth=False):
        url = API_URL + path

        if method == "GET":
            if requires_auth:
                headers = self._get_auth_headers()
            else:
                headers = {}
            response = requests.get(url, headers=headers)
        elif method == 'POST':
            headers = self._get_auth_headers()
            response = requests.post(url, headers=headers)
        elif method == 'PUT':
            headers = self._get_auth_headers()
            response = requests.put(url, data=data, headers=headers)

        return response

<|edits_diff|>
--- packs/travisci/actions/lib/action.py
+++ packs/travisci/actions/lib/action.py
@@ -1,3 +1,5 @@
+import httplib
+
 import requests

 from st2actions.runners.pythonrunner import Action
<|current_version|>
import httplib

import requests

from st2actions.runners.pythonrunner import Action

API_URL = 'https://api.travis-ci.org'
HEADERS_ACCEPT = 'application/vnd.travis-ci.2+json'
CONTENT_TYPE = 'application/json'

class TravisCI(Action):
    def _get_auth_headers(self):
        headers = {}
        headers['Authorization'] = self.config['Authorization']
        headers['Content-Type'] = self.config['Content-Type']
        return headers

    def _perform_request(self, path, method, data=None, requires_auth=False):
        url = API_URL + path

        if method == "GET":
            if requires_auth:
                headers = self._get_auth_headers()
            else:
                headers = {}
            response = requests.get(url, headers=headers)
        elif method == 'POST':
            headers = self._get_auth_headers()
            response = requests.post(url, headers=headers)
        elif method == 'PUT':
            headers = self._get_auth_headers()
            response = requests.put(url, data=data, headers=headers)

        return response

<|next_version|>
import httplib

import requests

from st2actions.runners.pythonrunner import Action

API_URL = 'https://api.travis-ci.org'
HEADERS_ACCEPT = 'application/vnd.travis-ci.2+json'
CONTENT_TYPE = 'application/json'

class TravisCI(Action):
    def _get_auth_headers(self):
        headers = {}
        headers['Authorization'] = self.config['Authorization']
        headers['Content-Type'] = self.config['Content-Type']
        return headers

    def _perform_request(self, path, method, data=None, requires_auth=False):
        url = API_URL + path

        if method == "GET":
            if requires_auth:
                headers = self._get_auth_headers()
            else:
                headers = {}
            response = requests.get(url, headers=headers)
        elif method == 'POST':
            headers = self._get_auth_headers()
            response = requests.post(url, headers=headers)
        elif method == 'PUT':
            headers = self._get_auth_headers()
            response = requests.put(url, data=data, headers=headers)

        if response.status_code in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
            msg = ('Invalid or missing Travis CI auth token. Make sure you have'
                   'specified valid token in the config file')
            raise Exception(msg)

        return response


Add recaptcha to signup page

Add recaptcha to signup page

Signup page is currently not used, but
doing it now in case it is forgotten later.

--- dthm4kaiako/users/forms.py
+++ dthm4kaiako/users/forms.py
@@ -2,12 +2,16 @@

 from django.forms import ModelForm
 from django.contrib.auth import get_user_model, forms
+from captcha.fields import ReCaptchaField
+from captcha.widgets import ReCaptchaV3

 User = get_user_model()

 class SignupForm(ModelForm):
     """Sign up for user registration."""
+
+    captcha = ReCaptchaField(widget=ReCaptchaV3, label='')

     class Meta:
         """Metadata for SignupForm class."""

<|original_code|>
"""Forms for user application."""

from django.forms import ModelForm
from django.contrib.auth import get_user_model, forms

User = get_user_model()

class SignupForm(ModelForm):
    """Sign up for user registration."""

    class Meta:
        """Metadata for SignupForm class."""

        model = get_user_model()
        fields = ['first_name', 'last_name']

    def signup(self, request, user):
        """Extra logic when a user signs up.

        Required by django-allauth.
        """
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.save()

class UserChangeForm(forms.UserChangeForm):
    """Form class for changing user."""

    class Meta(forms.UserChangeForm.Meta):
        """Metadata for UserChangeForm class."""

        model = User
        fields = ('email', 'last_name')

class UserCreationForm(forms.UserCreationForm):
    """Form class for creating user."""

    class Meta(forms.UserCreationForm.Meta):
        """Metadata for UserCreationForm class."""

        model = User
        fields = ('email', 'first_name', 'last_name')

<|edits_diff|>
--- dthm4kaiako/users/forms.py
+++ dthm4kaiako/users/forms.py
@@ -2,6 +2,8 @@

 from django.forms import ModelForm
 from django.contrib.auth import get_user_model, forms
+from captcha.fields import ReCaptchaField
+from captcha.widgets import ReCaptchaV3

 User = get_user_model()

<|current_version|>
"""Forms for user application."""

from django.forms import ModelForm
from django.contrib.auth import get_user_model, forms
from captcha.fields import ReCaptchaField
from captcha.widgets import ReCaptchaV3

User = get_user_model()

class SignupForm(ModelForm):
    """Sign up for user registration."""

    class Meta:
        """Metadata for SignupForm class."""

        model = get_user_model()
        fields = ['first_name', 'last_name']

    def signup(self, request, user):
        """Extra logic when a user signs up.

        Required by django-allauth.
        """
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.save()

class UserChangeForm(forms.UserChangeForm):
    """Form class for changing user."""

    class Meta(forms.UserChangeForm.Meta):
        """Metadata for UserChangeForm class."""

        model = User
        fields = ('email', 'last_name')

class UserCreationForm(forms.UserCreationForm):
    """Form class for creating user."""

    class Meta(forms.UserCreationForm.Meta):
        """Metadata for UserCreationForm class."""

        model = User
        fields = ('email', 'first_name', 'last_name')

<|next_version|>
"""Forms for user application."""

from django.forms import ModelForm
from django.contrib.auth import get_user_model, forms
from captcha.fields import ReCaptchaField
from captcha.widgets import ReCaptchaV3

User = get_user_model()

class SignupForm(ModelForm):
    """Sign up for user registration."""

    captcha = ReCaptchaField(widget=ReCaptchaV3, label='')

    class Meta:
        """Metadata for SignupForm class."""

        model = get_user_model()
        fields = ['first_name', 'last_name']

    def signup(self, request, user):
        """Extra logic when a user signs up.

        Required by django-allauth.
        """
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.save()

class UserChangeForm(forms.UserChangeForm):
    """Form class for changing user."""

    class Meta(forms.UserChangeForm.Meta):
        """Metadata for UserChangeForm class."""

        model = User
        fields = ('email', 'last_name')

class UserCreationForm(forms.UserCreationForm):
    """Form class for creating user."""

    class Meta(forms.UserCreationForm.Meta):
        """Metadata for UserCreationForm class."""

        model = User
        fields = ('email', 'first_name', 'last_name')


Disable test on Python 2.6.

Disable test on Python 2.6.

--- tests/test_invocation.py
+++ tests/test_invocation.py
@@ -2,7 +2,10 @@
 import subprocess
 import re

+import pytest

+
+@pytest.mark.skipif(sys.version_info < (2, 7), reason="check_output not available")
 def test_runpy_invoke():
     """
     Ensure honcho can also be invoked using runpy (python -m)

<|original_code|>
import sys
import subprocess
import re

def test_runpy_invoke():
    """
    Ensure honcho can also be invoked using runpy (python -m)
    """
    cmd = [sys.executable, '-m', 'honcho', 'version']
    output = subprocess.check_output(cmd, universal_newlines=True)
    assert re.match(r'honcho \d\.\d\.\d.*\n', output)

<|edits_diff|>
--- tests/test_invocation.py
+++ tests/test_invocation.py
@@ -2,6 +2,7 @@
 import subprocess
 import re

+import pytest

 def test_runpy_invoke():
     """
<|current_version|>
import sys
import subprocess
import re

import pytest

def test_runpy_invoke():
    """
    Ensure honcho can also be invoked using runpy (python -m)
    """
    cmd = [sys.executable, '-m', 'honcho', 'version']
    output = subprocess.check_output(cmd, universal_newlines=True)
    assert re.match(r'honcho \d\.\d\.\d.*\n', output)

<|next_version|>
import sys
import subprocess
import re

import pytest

@pytest.mark.skipif(sys.version_info < (2, 7), reason="check_output not available")
def test_runpy_invoke():
    """
    Ensure honcho can also be invoked using runpy (python -m)
    """
    cmd = [sys.executable, '-m', 'honcho', 'version']
    output = subprocess.check_output(cmd, universal_newlines=True)
    assert re.match(r'honcho \d\.\d\.\d.*\n', output)


Add function to convert fraction to decimal

--- openprocurement/tender/esco/utils.py
+++ openprocurement/tender/esco/utils.py
@@ -1,6 +1,10 @@
 # -*- coding: utf-8 -*-
+from decimal import Decimal
 from openprocurement.api.utils import get_now

 def request_get_now(request):
     return get_now()
+
+def to_decimal(fraction):
+    return Decimal(fraction.numerator) / Decimal(fraction.denominator)

<|original_code|>
# -*- coding: utf-8 -*-
from openprocurement.api.utils import get_now

def request_get_now(request):
    return get_now()

<|edits_diff|>
--- openprocurement/tender/esco/utils.py
+++ openprocurement/tender/esco/utils.py
@@ -1,4 +1,5 @@
 # -*- coding: utf-8 -*-
+from decimal import Decimal
 from openprocurement.api.utils import get_now

<|current_version|>
# -*- coding: utf-8 -*-
from decimal import Decimal
from openprocurement.api.utils import get_now

def request_get_now(request):
    return get_now()

<|next_version|>
# -*- coding: utf-8 -*-
from decimal import Decimal
from openprocurement.api.utils import get_now

def request_get_now(request):
    return get_now()

def to_decimal(fraction):
    return Decimal(fraction.numerator) / Decimal(fraction.denominator)


Delete material package temp file after creation

--- indico/modules/attachments/tasks.py
+++ indico/modules/attachments/tasks.py
@@ -4,6 +4,8 @@
 # Indico is free software; you can redistribute it and/or
 # modify it under the terms of the MIT License; see the
 # LICENSE file for more details.
+
+import os

 from indico.core.celery import celery
 from indico.core.db import db
@@ -23,4 +25,5 @@
     f.save(context, generated_zip)
     db.session.add(f)
     db.session.commit()
+    os.unlink(generated_zip.name)
     return f.signed_download_url

<|original_code|>
# This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.

from indico.core.celery import celery
from indico.core.db import db
from indico.modules.attachments.models.attachments import Attachment
from indico.modules.files.models.files import File

@celery.task(ignore_result=False)
def generate_materials_package(attachment_ids, event):
    from indico.modules.attachments.controllers.event_package import AttachmentPackageGeneratorMixin
    attachments = Attachment.query.filter(Attachment.id.in_(attachment_ids)).all()
    attachment_package_mixin = AttachmentPackageGeneratorMixin()
    attachment_package_mixin.event = event
    generated_zip = attachment_package_mixin._generate_zip_file(attachments, return_file=True)
    f = File(filename='material-package.zip', content_type='application/zip', meta={'event_id': event.id})
    context = ('event', event.id, 'attachment-package')
    f.save(context, generated_zip)
    db.session.add(f)
    db.session.commit()
    return f.signed_download_url

<|edits_diff|>
--- indico/modules/attachments/tasks.py
+++ indico/modules/attachments/tasks.py
@@ -4,6 +4,8 @@
 # Indico is free software; you can redistribute it and/or
 # modify it under the terms of the MIT License; see the
 # LICENSE file for more details.
+
+import os

 from indico.core.celery import celery
 from indico.core.db import db
<|current_version|>
# This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.

import os

from indico.core.celery import celery
from indico.core.db import db
from indico.modules.attachments.models.attachments import Attachment
from indico.modules.files.models.files import File

@celery.task(ignore_result=False)
def generate_materials_package(attachment_ids, event):
    from indico.modules.attachments.controllers.event_package import AttachmentPackageGeneratorMixin
    attachments = Attachment.query.filter(Attachment.id.in_(attachment_ids)).all()
    attachment_package_mixin = AttachmentPackageGeneratorMixin()
    attachment_package_mixin.event = event
    generated_zip = attachment_package_mixin._generate_zip_file(attachments, return_file=True)
    f = File(filename='material-package.zip', content_type='application/zip', meta={'event_id': event.id})
    context = ('event', event.id, 'attachment-package')
    f.save(context, generated_zip)
    db.session.add(f)
    db.session.commit()
    return f.signed_download_url

<|next_version|>
# This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.

import os

from indico.core.celery import celery
from indico.core.db import db
from indico.modules.attachments.models.attachments import Attachment
from indico.modules.files.models.files import File

@celery.task(ignore_result=False)
def generate_materials_package(attachment_ids, event):
    from indico.modules.attachments.controllers.event_package import AttachmentPackageGeneratorMixin
    attachments = Attachment.query.filter(Attachment.id.in_(attachment_ids)).all()
    attachment_package_mixin = AttachmentPackageGeneratorMixin()
    attachment_package_mixin.event = event
    generated_zip = attachment_package_mixin._generate_zip_file(attachments, return_file=True)
    f = File(filename='material-package.zip', content_type='application/zip', meta={'event_id': event.id})
    context = ('event', event.id, 'attachment-package')
    f.save(context, generated_zip)
    db.session.add(f)
    db.session.commit()
    os.unlink(generated_zip.name)
    return f.signed_download_url


Add rudimentary string support and a token for '=' sign.

--- lexer.py
+++ lexer.py
@@ -3,9 +3,11 @@

 tokens = ( 'SECTION',
            'IDENTIFIER',
+           'STRING',
            'LBRACE',
            'RBRACE',
            'SEMI',
+           'EQU',
            'TRUE',
            'FALSE' )

@@ -26,8 +28,17 @@
     r'[a-zA-Z\-0-9]+'
     return t

+def t_STRING(t):
+    r'(\".*\"|\'.*\')'
+    t.value = t.value[1:-1]
+    return t
+
 def t_LBRACE(t):
     r'{'
+    return t
+
+def t_EQU(t):
+    r'='
     return t

 def t_RBRACE(t):

<|original_code|>
import ply.lex as lex
import re

tokens = ( 'SECTION',
           'IDENTIFIER',
           'LBRACE',
           'RBRACE',
           'SEMI',
           'TRUE',
           'FALSE' )

def t_SECTION(t):
    r'section'
    return t

def t_TRUE(t):
    r'(true|1)'
    return t

def t_FALSE(t):
    r'(false|0)'
    return t

def t_IDENTIFIER(t):
    r'[a-zA-Z\-0-9]+'
    return t

def t_LBRACE(t):
    r'{'
    return t

def t_RBRACE(t):
    r'}'
    return t

def t_SEMI(t):
    r';'
    return t

def t_NEWLINE(t):
    r'\n+'

    t.lexer.lineno += len(t.value)
    return t

t_ignore = ' \t\n'

# Error handling rule
def t_error(t):
    print("Illegal character '{0}' at line {1}".format(t.value[0], t.lineno))
    t.lexer.skip(1)

lexer = lex.lex()

<|edits_diff|>
--- lexer.py
+++ lexer.py
@@ -3,9 +3,11 @@

 tokens = ( 'SECTION',
            'IDENTIFIER',
+           'STRING',
            'LBRACE',
            'RBRACE',
            'SEMI',
+           'EQU',
            'TRUE',
            'FALSE' )

@@ -24,6 +26,11 @@

 def t_IDENTIFIER(t):
     r'[a-zA-Z\-0-9]+'
+    return t
+
+def t_STRING(t):
+    r'(\".*\"|\'.*\')'
+    t.value = t.value[1:-1]
     return t

 def t_LBRACE(t):
<|current_version|>
import ply.lex as lex
import re

tokens = ( 'SECTION',
           'IDENTIFIER',
           'STRING',
           'LBRACE',
           'RBRACE',
           'SEMI',
           'EQU',
           'TRUE',
           'FALSE' )

def t_SECTION(t):
    r'section'
    return t

def t_TRUE(t):
    r'(true|1)'
    return t

def t_FALSE(t):
    r'(false|0)'
    return t

def t_IDENTIFIER(t):
    r'[a-zA-Z\-0-9]+'
    return t

def t_STRING(t):
    r'(\".*\"|\'.*\')'
    t.value = t.value[1:-1]
    return t

def t_LBRACE(t):
    r'{'
    return t

def t_RBRACE(t):
    r'}'
    return t

def t_SEMI(t):
    r';'
    return t

def t_NEWLINE(t):
    r'\n+'

    t.lexer.lineno += len(t.value)
    return t

t_ignore = ' \t\n'

# Error handling rule
def t_error(t):
    print("Illegal character '{0}' at line {1}".format(t.value[0], t.lineno))
    t.lexer.skip(1)

lexer = lex.lex()

<|next_version|>
import ply.lex as lex
import re

tokens = ( 'SECTION',
           'IDENTIFIER',
           'STRING',
           'LBRACE',
           'RBRACE',
           'SEMI',
           'EQU',
           'TRUE',
           'FALSE' )

def t_SECTION(t):
    r'section'
    return t

def t_TRUE(t):
    r'(true|1)'
    return t

def t_FALSE(t):
    r'(false|0)'
    return t

def t_IDENTIFIER(t):
    r'[a-zA-Z\-0-9]+'
    return t

def t_STRING(t):
    r'(\".*\"|\'.*\')'
    t.value = t.value[1:-1]
    return t

def t_LBRACE(t):
    r'{'
    return t

def t_EQU(t):
    r'='
    return t

def t_RBRACE(t):
    r'}'
    return t

def t_SEMI(t):
    r';'
    return t

def t_NEWLINE(t):
    r'\n+'

    t.lexer.lineno += len(t.value)
    return t

t_ignore = ' \t\n'

# Error handling rule
def t_error(t):
    print("Illegal character '{0}' at line {1}".format(t.value[0], t.lineno))
    t.lexer.skip(1)

lexer = lex.lex()


Make main program throw warning on python2.

--- pycalc.py
+++ pycalc.py
@@ -1,4 +1,10 @@
+# vim: set fileencoding=utf-8
+
 import sys
+
+if sys.version_info.major < 3:
+    print("This program is for python version 3 only.")
+    sys.exit(3)

 import lexer
 import execute

<|original_code|>
import sys

import lexer
import execute

while True:
    instr = input("» ")
    toks = lexer.to_toks(instr)
    rpn = lexer.to_rpn(toks)

    result = execute.eval_rpn(rpn)

    if result is not None:
        print(result)

    if len(sys.argv) >= 2:
        break

<|edits_diff|>
--- pycalc.py
+++ pycalc.py
@@ -1,3 +1,5 @@
+# vim: set fileencoding=utf-8
+
 import sys

 import lexer
<|current_version|>
# vim: set fileencoding=utf-8

import sys

import lexer
import execute

while True:
    instr = input("» ")
    toks = lexer.to_toks(instr)
    rpn = lexer.to_rpn(toks)

    result = execute.eval_rpn(rpn)

    if result is not None:
        print(result)

    if len(sys.argv) >= 2:
        break

<|next_version|>
# vim: set fileencoding=utf-8

import sys

if sys.version_info.major < 3:
    print("This program is for python version 3 only.")
    sys.exit(3)

import lexer
import execute

while True:
    instr = input("» ")
    toks = lexer.to_toks(instr)
    rpn = lexer.to_rpn(toks)

    result = execute.eval_rpn(rpn)

    if result is not None:
        print(result)

    if len(sys.argv) >= 2:
        break


Add backuping config files for Hitman: Codename 47

--- plugins/Hitman_Codename_47.py
+++ plugins/Hitman_Codename_47.py
@@ -9,9 +9,11 @@

     def backup(self, _):
         _.add_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav')
+        _.add_files('Config', os.path.join(SteamGamesPath, 'Hitman Codename 47'), ['Hitman.cfg', 'hitman.ini'])

     def restore(self, _):
         _.restore_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav')
+        _.restore_files('Config', os.path.join(SteamGamesPath, 'Hitman Codename 47'), ['Hitman.cfg', 'hitman.ini'])

     def detect(self):
         if os.path.isdir(os.path.join(SteamGamesPath, 'Hitman Codename 47')):

<|original_code|>
import os
from lib.base_plugin import BasePlugin
from lib.paths import SteamGamesPath

class HitmanCodename47Plugin(BasePlugin):
    Name = "Hitman: Codename 47"
    support_os = ["Windows"]

    def backup(self, _):
        _.add_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav')

    def restore(self, _):
        _.restore_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav')

    def detect(self):
        if os.path.isdir(os.path.join(SteamGamesPath, 'Hitman Codename 47')):
            return True
        return False

<|edits_diff|>
--- plugins/Hitman_Codename_47.py
+++ plugins/Hitman_Codename_47.py
@@ -9,6 +9,7 @@

     def backup(self, _):
         _.add_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav')
+        _.add_files('Config', os.path.join(SteamGamesPath, 'Hitman Codename 47'), ['Hitman.cfg', 'hitman.ini'])

     def restore(self, _):
         _.restore_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav')
<|current_version|>
import os
from lib.base_plugin import BasePlugin
from lib.paths import SteamGamesPath

class HitmanCodename47Plugin(BasePlugin):
    Name = "Hitman: Codename 47"
    support_os = ["Windows"]

    def backup(self, _):
        _.add_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav')
        _.add_files('Config', os.path.join(SteamGamesPath, 'Hitman Codename 47'), ['Hitman.cfg', 'hitman.ini'])

    def restore(self, _):
        _.restore_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav')

    def detect(self):
        if os.path.isdir(os.path.join(SteamGamesPath, 'Hitman Codename 47')):
            return True
        return False

<|next_version|>
import os
from lib.base_plugin import BasePlugin
from lib.paths import SteamGamesPath

class HitmanCodename47Plugin(BasePlugin):
    Name = "Hitman: Codename 47"
    support_os = ["Windows"]

    def backup(self, _):
        _.add_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav')
        _.add_files('Config', os.path.join(SteamGamesPath, 'Hitman Codename 47'), ['Hitman.cfg', 'hitman.ini'])

    def restore(self, _):
        _.restore_files('Save', os.path.join(SteamGamesPath, 'Hitman Codename 47'), 'Hitman.sav')
        _.restore_files('Config', os.path.join(SteamGamesPath, 'Hitman Codename 47'), ['Hitman.cfg', 'hitman.ini'])

    def detect(self):
        if os.path.isdir(os.path.join(SteamGamesPath, 'Hitman Codename 47')):
            return True
        return False


Apply linesman profiler to the wsgi app

Apply linesman profiler to the wsgi app

I fully expect this commit to be backed out when we get the profiling
stuff sorted out, but thankfully, this profiler can be disabled for a
live site.

check out http://<site>/__profiler__ after installing linesman, and
running the uwsgi server

--- ureport_project/wsgi_app.py
+++ ureport_project/wsgi_app.py
@@ -12,5 +12,7 @@
 print sys.path

 from django.core.handlers.wsgi import WSGIHandler
+from linesman.middleware import make_linesman_middleware

 application = WSGIHandler()
+application = make_linesman_middleware(application)

<|original_code|>
# wsgi_app.py
import sys, os

filedir = os.path.dirname(__file__)
sys.path.append(os.path.join(filedir))

#print sys.path

os.environ["CELERY_LOADER"] = "django"
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
import sys
print sys.path

from django.core.handlers.wsgi import WSGIHandler

application = WSGIHandler()

<|edits_diff|>
--- ureport_project/wsgi_app.py
+++ ureport_project/wsgi_app.py
@@ -12,5 +12,6 @@
 print sys.path

 from django.core.handlers.wsgi import WSGIHandler
+from linesman.middleware import make_linesman_middleware

 application = WSGIHandler()
<|current_version|>
# wsgi_app.py
import sys, os

filedir = os.path.dirname(__file__)
sys.path.append(os.path.join(filedir))

#print sys.path

os.environ["CELERY_LOADER"] = "django"
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
import sys
print sys.path

from django.core.handlers.wsgi import WSGIHandler
from linesman.middleware import make_linesman_middleware

application = WSGIHandler()

<|next_version|>
# wsgi_app.py
import sys, os

filedir = os.path.dirname(__file__)
sys.path.append(os.path.join(filedir))

#print sys.path

os.environ["CELERY_LOADER"] = "django"
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
import sys
print sys.path

from django.core.handlers.wsgi import WSGIHandler
from linesman.middleware import make_linesman_middleware

application = WSGIHandler()
application = make_linesman_middleware(application)


Add typecheck to Parameter function

Add typecheck to Parameter function

--- chainer/functions/parameter.py
+++ chainer/functions/parameter.py
@@ -1,6 +1,7 @@
 import numpy

 from chainer import function
+from chainer.utils import type_check

 class Parameter(function.Function):
@@ -21,6 +22,9 @@
         self.W = array
         self.gW = numpy.empty_like(array)

+    def check_type_forward(self, in_types):
+        type_check.expect(in_types.size() == 0)
+
     def forward(self, x):
         return self.W,

<|original_code|>
import numpy

from chainer import function

class Parameter(function.Function):

    """Function that outputs its weight array.

    This is a parameterized function that takes no input and returns a variable
    holding a shallow copy of the parameter array.

    Args:
        array: Initial parameter array.

    """
    parameter_names = 'W',
    gradient_names = 'gW',

    def __init__(self, array):
        self.W = array
        self.gW = numpy.empty_like(array)

    def forward(self, x):
        return self.W,

    def backward(self, x, gy):
        self.gW += gy[0]
        return ()

<|edits_diff|>
--- chainer/functions/parameter.py
+++ chainer/functions/parameter.py
@@ -1,6 +1,7 @@
 import numpy

 from chainer import function
+from chainer.utils import type_check

 class Parameter(function.Function):
<|current_version|>
import numpy

from chainer import function
from chainer.utils import type_check

class Parameter(function.Function):

    """Function that outputs its weight array.

    This is a parameterized function that takes no input and returns a variable
    holding a shallow copy of the parameter array.

    Args:
        array: Initial parameter array.

    """
    parameter_names = 'W',
    gradient_names = 'gW',

    def __init__(self, array):
        self.W = array
        self.gW = numpy.empty_like(array)

    def forward(self, x):
        return self.W,

    def backward(self, x, gy):
        self.gW += gy[0]
        return ()

<|next_version|>
import numpy

from chainer import function
from chainer.utils import type_check

class Parameter(function.Function):

    """Function that outputs its weight array.

    This is a parameterized function that takes no input and returns a variable
    holding a shallow copy of the parameter array.

    Args:
        array: Initial parameter array.

    """
    parameter_names = 'W',
    gradient_names = 'gW',

    def __init__(self, array):
        self.W = array
        self.gW = numpy.empty_like(array)

    def check_type_forward(self, in_types):
        type_check.expect(in_types.size() == 0)

    def forward(self, x):
        return self.W,

    def backward(self, x, gy):
        self.gW += gy[0]
        return ()


Define Post model related fields.

Ch03: Define Post model related fields. [skip ci]

    https://docs.djangoproject.com/en/1.8/ref/models/fields/#manytomanyfield

Blog Posts may be about multiple Startups, just as Startups may be
written about multiple times. Posts may also be categorized by multiple
Tags, just as Tags may be used multiple times to categorize different
Posts.

--- blog/models.py
+++ blog/models.py
@@ -1,4 +1,6 @@
 from django.db import models
+
+from organizer.models import Startup, Tag

 # Model Field Reference
@@ -10,3 +12,5 @@
     slug = models.SlugField()
     text = models.TextField()
     pub_date = models.DateField()
+    tags = models.ManyToManyField(Tag)
+    startups = models.ManyToManyField(Startup)

<|original_code|>
from django.db import models

# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/

class Post(models.Model):
    title = models.CharField(max_length=63)
    slug = models.SlugField()
    text = models.TextField()
    pub_date = models.DateField()

<|edits_diff|>
--- blog/models.py
+++ blog/models.py
@@ -1,4 +1,6 @@
 from django.db import models
+
+from organizer.models import Startup, Tag

 # Model Field Reference
<|current_version|>
from django.db import models

from organizer.models import Startup, Tag

# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/

class Post(models.Model):
    title = models.CharField(max_length=63)
    slug = models.SlugField()
    text = models.TextField()
    pub_date = models.DateField()

<|next_version|>
from django.db import models

from organizer.models import Startup, Tag

# Model Field Reference
# https://docs.djangoproject.com/en/1.8/ref/models/fields/

class Post(models.Model):
    title = models.CharField(max_length=63)
    slug = models.SlugField()
    text = models.TextField()
    pub_date = models.DateField()
    tags = models.ManyToManyField(Tag)
    startups = models.ManyToManyField(Startup)


Use the login manager and set a default app secret key

--- app.tmpl/__init__.py
+++ app.tmpl/__init__.py
@@ -4,7 +4,12 @@

 from flask import Flask
+from flask_login import LoginManager
 app = Flask(__name__)
+app.secret_key = 'default-secret-key'
+login_manager = LoginManager()
+login_manager.init_app(app)
+login_manager.login_view = 'login'

 # Import anything that depended on `app`
 from {{PROJECTNAME}}.views import *

<|original_code|>
# Main application file
#
# Copyright (c) 2015, Alexandre Hamelin <alexandre.hamelin gmail.com>

from flask import Flask
app = Flask(__name__)

# Import anything that depended on `app`
from {{PROJECTNAME}}.views import *
from {{PROJECTNAME}}.models import *

<|edits_diff|>
--- app.tmpl/__init__.py
+++ app.tmpl/__init__.py
@@ -4,6 +4,7 @@

 from flask import Flask
+from flask_login import LoginManager
 app = Flask(__name__)

 # Import anything that depended on `app`
<|current_version|>
# Main application file
#
# Copyright (c) 2015, Alexandre Hamelin <alexandre.hamelin gmail.com>

from flask import Flask
from flask_login import LoginManager
app = Flask(__name__)

# Import anything that depended on `app`
from {{PROJECTNAME}}.views import *
from {{PROJECTNAME}}.models import *

<|next_version|>
# Main application file
#
# Copyright (c) 2015, Alexandre Hamelin <alexandre.hamelin gmail.com>

from flask import Flask
from flask_login import LoginManager
app = Flask(__name__)
app.secret_key = 'default-secret-key'
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'

# Import anything that depended on `app`
from {{PROJECTNAME}}.views import *
from {{PROJECTNAME}}.models import *


Add default versions for trove and ironic

Change-Id: Ib7af38664cfbe75c78c70693117f1193c4beb7e6

--- os_client_config/defaults.py
+++ os_client_config/defaults.py
@@ -14,7 +14,9 @@

 _defaults = dict(
     auth_type='password',
+    baremetal_api_version='1',
     compute_api_version='2',
+    database_api_version='1.0',
     floating_ip_source='neutron',
     identity_api_version='2',
     image_api_use_tasks=False,

<|original_code|>
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
#
# 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.

_defaults = dict(
    auth_type='password',
    compute_api_version='2',
    floating_ip_source='neutron',
    identity_api_version='2',
    image_api_use_tasks=False,
    image_api_version='1',
    network_api_version='2',
    object_api_version='1',
    volume_api_version='1',
)

<|edits_diff|>
--- os_client_config/defaults.py
+++ os_client_config/defaults.py
@@ -14,6 +14,7 @@

 _defaults = dict(
     auth_type='password',
+    baremetal_api_version='1',
     compute_api_version='2',
     floating_ip_source='neutron',
     identity_api_version='2',
<|current_version|>
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
#
# 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.

_defaults = dict(
    auth_type='password',
    baremetal_api_version='1',
    compute_api_version='2',
    floating_ip_source='neutron',
    identity_api_version='2',
    image_api_use_tasks=False,
    image_api_version='1',
    network_api_version='2',
    object_api_version='1',
    volume_api_version='1',
)

<|next_version|>
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
#
# 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.

_defaults = dict(
    auth_type='password',
    baremetal_api_version='1',
    compute_api_version='2',
    database_api_version='1.0',
    floating_ip_source='neutron',
    identity_api_version='2',
    image_api_use_tasks=False,
    image_api_version='1',
    network_api_version='2',
    object_api_version='1',
    volume_api_version='1',
)


Add test for BadCharError exception.

Add test for BadCharError exception.

--- tests/test_errors.py
+++ tests/test_errors.py
@@ -3,6 +3,7 @@

 from pyxl.codec.register import pyxl_decode
 from pyxl.codec.parser import ParseError
+from pyxl.codec.html_tokenizer import BadCharError

 def test_malformed_if():
     with pytest.raises(ParseError):
@@ -29,3 +30,7 @@
                 <if cond="{true}">foo</if>
                 <else><else>bar</else></else>
             </frag>""")
+
+def test_bad_char():
+    with pytest.raises(BadCharError):
+        pyxl_decode(b"""<_bad_element></lm>""")

<|original_code|>
# coding: pyxl
import pytest

from pyxl.codec.register import pyxl_decode
from pyxl.codec.parser import ParseError

def test_malformed_if():
    with pytest.raises(ParseError):
        pyxl_decode(b"""
            <frag>
                <if cond="{true}">foo</if>
                this is incorrect!
                <else>bar</else>
            </frag>""")

def test_multiple_else():
    with pytest.raises(ParseError):
        pyxl_decode(b"""
            <frag>
                <if cond="{true}">foo</if>
                <else>bar</else>
                <else>baz</else>
             </frag>""")

def test_nested_else():
    with pytest.raises(ParseError):
        pyxl_decode(b"""
            <frag>
                <if cond="{true}">foo</if>
                <else><else>bar</else></else>
            </frag>""")

<|edits_diff|>
--- tests/test_errors.py
+++ tests/test_errors.py
@@ -3,6 +3,7 @@

 from pyxl.codec.register import pyxl_decode
 from pyxl.codec.parser import ParseError
+from pyxl.codec.html_tokenizer import BadCharError

 def test_malformed_if():
     with pytest.raises(ParseError):
<|current_version|>
# coding: pyxl
import pytest

from pyxl.codec.register import pyxl_decode
from pyxl.codec.parser import ParseError
from pyxl.codec.html_tokenizer import BadCharError

def test_malformed_if():
    with pytest.raises(ParseError):
        pyxl_decode(b"""
            <frag>
                <if cond="{true}">foo</if>
                this is incorrect!
                <else>bar</else>
            </frag>""")

def test_multiple_else():
    with pytest.raises(ParseError):
        pyxl_decode(b"""
            <frag>
                <if cond="{true}">foo</if>
                <else>bar</else>
                <else>baz</else>
             </frag>""")

def test_nested_else():
    with pytest.raises(ParseError):
        pyxl_decode(b"""
            <frag>
                <if cond="{true}">foo</if>
                <else><else>bar</else></else>
            </frag>""")

<|next_version|>
# coding: pyxl
import pytest

from pyxl.codec.register import pyxl_decode
from pyxl.codec.parser import ParseError
from pyxl.codec.html_tokenizer import BadCharError

def test_malformed_if():
    with pytest.raises(ParseError):
        pyxl_decode(b"""
            <frag>
                <if cond="{true}">foo</if>
                this is incorrect!
                <else>bar</else>
            </frag>""")

def test_multiple_else():
    with pytest.raises(ParseError):
        pyxl_decode(b"""
            <frag>
                <if cond="{true}">foo</if>
                <else>bar</else>
                <else>baz</else>
             </frag>""")

def test_nested_else():
    with pytest.raises(ParseError):
        pyxl_decode(b"""
            <frag>
                <if cond="{true}">foo</if>
                <else><else>bar</else></else>
            </frag>""")

def test_bad_char():
    with pytest.raises(BadCharError):
        pyxl_decode(b"""<_bad_element></lm>""")


Fix aqdb rebuild to work when not using AQDCONF env variable.

--- tests/aqdb/test_rebuild.py
+++ tests/aqdb/test_rebuild.py
@@ -10,12 +10,15 @@

 from subprocess import Popen, PIPE

+from aquilon.config import Config
+
 class TestRebuild(unittest.TestCase):

     def testrebuild(self):
         env = {}
         for (key, value) in os.environ.items():
             env[key] = value
+        env["AQDCONF"] = Config().baseconfig

         cmd = ['./build_db.py', '--delete', '--populate']

<|original_code|>
#!/ms/dist/python/PROJ/core/2.5.4-0/bin/python
"""Test module for rebuilding the database."""

import os
import __init__

import aquilon.aqdb.depends
import nose
import unittest

from subprocess import Popen, PIPE

class TestRebuild(unittest.TestCase):

    def testrebuild(self):
        env = {}
        for (key, value) in os.environ.items():
            env[key] = value

        cmd = ['./build_db.py', '--delete', '--populate']

        _DIR = os.path.dirname(os.path.realpath(__file__))
        p = Popen(cmd, stdout=1, stderr=2, env=env, cwd=_DIR)
        (out, err) = p.communicate()

        self.assertEqual(p.returncode, 0, "Database rebuild failed:\n%s" % err)

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

# Copyright (C) 2008 Morgan Stanley
# This module is part of Aquilon

# ex: set expandtab softtabstop=4 shiftwidth=4: -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-

<|edits_diff|>
--- tests/aqdb/test_rebuild.py
+++ tests/aqdb/test_rebuild.py
@@ -9,6 +9,8 @@
 import unittest

 from subprocess import Popen, PIPE
+
+from aquilon.config import Config

 class TestRebuild(unittest.TestCase):

<|current_version|>
#!/ms/dist/python/PROJ/core/2.5.4-0/bin/python
"""Test module for rebuilding the database."""

import os
import __init__

import aquilon.aqdb.depends
import nose
import unittest

from subprocess import Popen, PIPE

from aquilon.config import Config

class TestRebuild(unittest.TestCase):

    def testrebuild(self):
        env = {}
        for (key, value) in os.environ.items():
            env[key] = value

        cmd = ['./build_db.py', '--delete', '--populate']

        _DIR = os.path.dirname(os.path.realpath(__file__))
        p = Popen(cmd, stdout=1, stderr=2, env=env, cwd=_DIR)
        (out, err) = p.communicate()

        self.assertEqual(p.returncode, 0, "Database rebuild failed:\n%s" % err)

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

# Copyright (C) 2008 Morgan Stanley
# This module is part of Aquilon

# ex: set expandtab softtabstop=4 shiftwidth=4: -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-

<|next_version|>
#!/ms/dist/python/PROJ/core/2.5.4-0/bin/python
"""Test module for rebuilding the database."""

import os
import __init__

import aquilon.aqdb.depends
import nose
import unittest

from subprocess import Popen, PIPE

from aquilon.config import Config

class TestRebuild(unittest.TestCase):

    def testrebuild(self):
        env = {}
        for (key, value) in os.environ.items():
            env[key] = value
        env["AQDCONF"] = Config().baseconfig

        cmd = ['./build_db.py', '--delete', '--populate']

        _DIR = os.path.dirname(os.path.realpath(__file__))
        p = Popen(cmd, stdout=1, stderr=2, env=env, cwd=_DIR)
        (out, err) = p.communicate()

        self.assertEqual(p.returncode, 0, "Database rebuild failed:\n%s" % err)

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

# Copyright (C) 2008 Morgan Stanley
# This module is part of Aquilon

# ex: set expandtab softtabstop=4 shiftwidth=4: -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-


Add function for generating random id

Add function for generating random id

--- ckanext/orgdashboards/tests/helpers.py
+++ ckanext/orgdashboards/tests/helpers.py
@@ -1,3 +1,8 @@
+''' Helper methods for tests '''
+
+import string
+import random
+
 from ckan.tests import factories

@@ -25,3 +30,8 @@
     }

     return mock_data
+
+def id_generator(size=6, chars=string.ascii_lowercase + string.digits):
+    ''' Create random id which is a combination of letters and numbers '''
+
+    return ''.join(random.choice(chars) for _ in range(size))

<|original_code|>
from ckan.tests import factories

def create_mock_data(**kwargs):
    mock_data = {}

    mock_data['organization'] = factories.Organization()
    mock_data['organization_name'] = mock_data['organization']['name']
    mock_data['organization_id'] = mock_data['organization']['id']

    mock_data['dataset'] = factories.Dataset(owner_org=mock_data['organization_id'])
    mock_data['dataset_name'] = mock_data['dataset']['name']
    mock_data['package_id'] = mock_data['dataset']['id']

    mock_data['resource'] = factories.Resource(package_id=mock_data['package_id'])
    mock_data['resource_name'] = mock_data['resource']['name']
    mock_data['resource_id'] = mock_data['resource']['id']

    mock_data['resource_view'] = factories.ResourceView(
        resource_id=mock_data['resource_id'])
    mock_data['resource_view_title'] = mock_data['resource_view']['title']

    mock_data['context'] = {
        'user': factories._get_action_user_name(kwargs)
    }

    return mock_data
<|edits_diff|>
--- ckanext/orgdashboards/tests/helpers.py
+++ ckanext/orgdashboards/tests/helpers.py
@@ -25,3 +25,8 @@
     }

     return mock_data
+
+def id_generator(size=6, chars=string.ascii_lowercase + string.digits):
+    ''' Create random id which is a combination of letters and numbers '''
+
+    return ''.join(random.choice(chars) for _ in range(size))
<|current_version|>
from ckan.tests import factories

def create_mock_data(**kwargs):
    mock_data = {}

    mock_data['organization'] = factories.Organization()
    mock_data['organization_name'] = mock_data['organization']['name']
    mock_data['organization_id'] = mock_data['organization']['id']

    mock_data['dataset'] = factories.Dataset(owner_org=mock_data['organization_id'])
    mock_data['dataset_name'] = mock_data['dataset']['name']
    mock_data['package_id'] = mock_data['dataset']['id']

    mock_data['resource'] = factories.Resource(package_id=mock_data['package_id'])
    mock_data['resource_name'] = mock_data['resource']['name']
    mock_data['resource_id'] = mock_data['resource']['id']

    mock_data['resource_view'] = factories.ResourceView(
        resource_id=mock_data['resource_id'])
    mock_data['resource_view_title'] = mock_data['resource_view']['title']

    mock_data['context'] = {
        'user': factories._get_action_user_name(kwargs)
    }

    return mock_data

def id_generator(size=6, chars=string.ascii_lowercase + string.digits):
    ''' Create random id which is a combination of letters and numbers '''

    return ''.join(random.choice(chars) for _ in range(size))
<|next_version|>
''' Helper methods for tests '''

import string
import random

from ckan.tests import factories

def create_mock_data(**kwargs):
    mock_data = {}

    mock_data['organization'] = factories.Organization()
    mock_data['organization_name'] = mock_data['organization']['name']
    mock_data['organization_id'] = mock_data['organization']['id']

    mock_data['dataset'] = factories.Dataset(owner_org=mock_data['organization_id'])
    mock_data['dataset_name'] = mock_data['dataset']['name']
    mock_data['package_id'] = mock_data['dataset']['id']

    mock_data['resource'] = factories.Resource(package_id=mock_data['package_id'])
    mock_data['resource_name'] = mock_data['resource']['name']
    mock_data['resource_id'] = mock_data['resource']['id']

    mock_data['resource_view'] = factories.ResourceView(
        resource_id=mock_data['resource_id'])
    mock_data['resource_view_title'] = mock_data['resource_view']['title']

    mock_data['context'] = {
        'user': factories._get_action_user_name(kwargs)
    }

    return mock_data

def id_generator(size=6, chars=string.ascii_lowercase + string.digits):
    ''' Create random id which is a combination of letters and numbers '''

    return ''.join(random.choice(chars) for _ in range(size))


Use new README.rst as package long_description

--- setup.py
+++ setup.py
@@ -11,10 +11,15 @@
     sys.exit()

+with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as f:
+    readme = f.read()
+
+
 setup(
     name='sentry-sso-google',
     version='1.1',
     description='Google SSO support for Sentry',
+    long_description=readme,
     author='Educreations Engineering',
     author_email='engineering@educreations.com',
     url='https://github.com/educreations/sentry-sso-google',

<|original_code|>
#!/usr/bin/env python

import os
import sys

from setuptools import setup

if sys.argv[-1] == 'publish':
    os.system('python setup.py register sdist bdist_wheel upload')
    sys.exit()

setup(
    name='sentry-sso-google',
    version='1.1',
    description='Google SSO support for Sentry',
    author='Educreations Engineering',
    author_email='engineering@educreations.com',
    url='https://github.com/educreations/sentry-sso-google',
    install_requires=['sentry>=7.5'],
    packages=["sentry_sso_google"],
    license="MIT",
)

<|edits_diff|>
--- setup.py
+++ setup.py
@@ -11,6 +11,10 @@
     sys.exit()

+with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as f:
+    readme = f.read()
+
+
 setup(
     name='sentry-sso-google',
     version='1.1',
<|current_version|>
#!/usr/bin/env python

import os
import sys

from setuptools import setup

if sys.argv[-1] == 'publish':
    os.system('python setup.py register sdist bdist_wheel upload')
    sys.exit()

with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as f:
    readme = f.read()

setup(
    name='sentry-sso-google',
    version='1.1',
    description='Google SSO support for Sentry',
    author='Educreations Engineering',
    author_email='engineering@educreations.com',
    url='https://github.com/educreations/sentry-sso-google',
    install_requires=['sentry>=7.5'],
    packages=["sentry_sso_google"],
    license="MIT",
)

<|next_version|>
#!/usr/bin/env python

import os
import sys

from setuptools import setup

if sys.argv[-1] == 'publish':
    os.system('python setup.py register sdist bdist_wheel upload')
    sys.exit()

with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as f:
    readme = f.read()

setup(
    name='sentry-sso-google',
    version='1.1',
    description='Google SSO support for Sentry',
    long_description=readme,
    author='Educreations Engineering',
    author_email='engineering@educreations.com',
    url='https://github.com/educreations/sentry-sso-google',
    install_requires=['sentry>=7.5'],
    packages=["sentry_sso_google"],
    license="MIT",
)


Refactor test case into two classes

Refactor test case into two classes

--- tests/test_server.py
+++ tests/test_server.py
@@ -21,10 +21,14 @@
         os.close(self.db_fd)
         os.unlink(server.app.config['DATABASE'])

+
+class RootTestCase(ServerTestCase):
     def test_root(self):
         rv = self.app.get('/')
         self.assertEqual(rv.status_code, 200)

+
+class BookTestCase(ServerTestCase):
     def test_book_post(self):
         rv = self.app.put('/books', data={'isbn': 1234})
         self.assertEqual(rv.status_code, 200)

<|original_code|>
import os
import unittest
import tempfile

# Local modules
import library.server as server

class ServerTestCase(unittest.TestCase):

    @classmethod
    def setUp(self):
        self.db_fd, server.app.config['DATABASE'] = tempfile.mkstemp()
        server.app.config['TESTING'] = True
        self.app = server.app.test_client()
        with server.app.app_context():
            server.init_db()

    @classmethod
    def tearDown(self):
        os.close(self.db_fd)
        os.unlink(server.app.config['DATABASE'])

    def test_root(self):
        rv = self.app.get('/')
        self.assertEqual(rv.status_code, 200)

    def test_book_post(self):
        rv = self.app.put('/books', data={'isbn': 1234})
        self.assertEqual(rv.status_code, 200)
        rv = self.app.get('/books')
        self.assertEqual(rv.data, '1234')
        rv = self.app.put('/books', data={'isbn': 5678})
        self.assertEqual(rv.status_code, 200)

        rv = self.app.get('/books')
        self.assertEqual(rv.data, '5678 1234')

    def test_book_get(self):
        rv = self.app.get('/books')
        self.assertEqual(rv.status_code, 200)

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

<|edits_diff|>
--- tests/test_server.py
+++ tests/test_server.py
@@ -21,6 +21,8 @@
         os.close(self.db_fd)
         os.unlink(server.app.config['DATABASE'])

+
+class RootTestCase(ServerTestCase):
     def test_root(self):
         rv = self.app.get('/')
         self.assertEqual(rv.status_code, 200)
<|current_version|>
import os
import unittest
import tempfile

# Local modules
import library.server as server

class ServerTestCase(unittest.TestCase):

    @classmethod
    def setUp(self):
        self.db_fd, server.app.config['DATABASE'] = tempfile.mkstemp()
        server.app.config['TESTING'] = True
        self.app = server.app.test_client()
        with server.app.app_context():
            server.init_db()

    @classmethod
    def tearDown(self):
        os.close(self.db_fd)
        os.unlink(server.app.config['DATABASE'])

class RootTestCase(ServerTestCase):
    def test_root(self):
        rv = self.app.get('/')
        self.assertEqual(rv.status_code, 200)

    def test_book_post(self):
        rv = self.app.put('/books', data={'isbn': 1234})
        self.assertEqual(rv.status_code, 200)
        rv = self.app.get('/books')
        self.assertEqual(rv.data, '1234')
        rv = self.app.put('/books', data={'isbn': 5678})
        self.assertEqual(rv.status_code, 200)

        rv = self.app.get('/books')
        self.assertEqual(rv.data, '5678 1234')

    def test_book_get(self):
        rv = self.app.get('/books')
        self.assertEqual(rv.status_code, 200)

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

<|next_version|>
import os
import unittest
import tempfile

# Local modules
import library.server as server

class ServerTestCase(unittest.TestCase):

    @classmethod
    def setUp(self):
        self.db_fd, server.app.config['DATABASE'] = tempfile.mkstemp()
        server.app.config['TESTING'] = True
        self.app = server.app.test_client()
        with server.app.app_context():
            server.init_db()

    @classmethod
    def tearDown(self):
        os.close(self.db_fd)
        os.unlink(server.app.config['DATABASE'])

class RootTestCase(ServerTestCase):
    def test_root(self):
        rv = self.app.get('/')
        self.assertEqual(rv.status_code, 200)

class BookTestCase(ServerTestCase):
    def test_book_post(self):
        rv = self.app.put('/books', data={'isbn': 1234})
        self.assertEqual(rv.status_code, 200)
        rv = self.app.get('/books')
        self.assertEqual(rv.data, '1234')
        rv = self.app.put('/books', data={'isbn': 5678})
        self.assertEqual(rv.status_code, 200)

        rv = self.app.get('/books')
        self.assertEqual(rv.data, '5678 1234')

    def test_book_get(self):
        rv = self.app.get('/books')
        self.assertEqual(rv.status_code, 200)

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


Update RMG example liquid_phase with multiplicity label

--- examples/rmg/liquid_phase/input.py
+++ examples/rmg/liquid_phase/input.py
@@ -8,15 +8,22 @@
     kineticsEstimator = 'rate rules',
 )

+# Constraints on generated species
+generatedSpeciesConstraints(
+    maximumRadicalElectrons = 3,
+)
+
 # List of species
 species(
     label='octane',
+    multiplicity = 1,
     reactive=True,
     structure=SMILES("C(CCCCC)CC"),
 )

 species(
     label='oxygen',
+    multiplicity = 3,
     reactive=True,
     structure=SMILES("[O][O]"),
 )

<|original_code|>
# Data sources
database(
    thermoLibraries = ['primaryThermoLibrary'],
    reactionLibraries = [],
    seedMechanisms = [],
    kineticsDepositories = ['training'],
    kineticsFamilies = 'default',
    kineticsEstimator = 'rate rules',
)

# List of species
species(
    label='octane',
    reactive=True,
    structure=SMILES("C(CCCCC)CC"),
)

species(
    label='oxygen',
    reactive=True,
    structure=SMILES("[O][O]"),
)

# Reaction systems
liquidReactor(
    temperature=(500,'K'),
    initialConcentrations={
        "octane": (6.154e-3,'mol/cm^3'),
        "oxygen": (4.953e-6,'mol/cm^3')
    },
    terminationTime=(5,'s'),
)

solvation(
	solvent='octane'
)

simulator(
    atol=1e-16,
    rtol=1e-8,
)

model(
    toleranceKeepInEdge=1E-9,
    toleranceMoveToCore=0.001,
    toleranceInterruptSimulation=0.1,
    maximumEdgeSpecies=100000
)

options(
    units='si',
    saveRestartPeriod=None,
    drawMolecules=False,
    generatePlots=False,
    saveConcentrationProfiles=True,
)

<|edits_diff|>
--- examples/rmg/liquid_phase/input.py
+++ examples/rmg/liquid_phase/input.py
@@ -8,9 +8,15 @@
     kineticsEstimator = 'rate rules',
 )

+# Constraints on generated species
+generatedSpeciesConstraints(
+    maximumRadicalElectrons = 3,
+)
+
 # List of species
 species(
     label='octane',
+    multiplicity = 1,
     reactive=True,
     structure=SMILES("C(CCCCC)CC"),
 )
<|current_version|>
# Data sources
database(
    thermoLibraries = ['primaryThermoLibrary'],
    reactionLibraries = [],
    seedMechanisms = [],
    kineticsDepositories = ['training'],
    kineticsFamilies = 'default',
    kineticsEstimator = 'rate rules',
)

# Constraints on generated species
generatedSpeciesConstraints(
    maximumRadicalElectrons = 3,
)

# List of species
species(
    label='octane',
    multiplicity = 1,
    reactive=True,
    structure=SMILES("C(CCCCC)CC"),
)

species(
    label='oxygen',
    reactive=True,
    structure=SMILES("[O][O]"),
)

# Reaction systems
liquidReactor(
    temperature=(500,'K'),
    initialConcentrations={
        "octane": (6.154e-3,'mol/cm^3'),
        "oxygen": (4.953e-6,'mol/cm^3')
    },
    terminationTime=(5,'s'),
)

solvation(
	solvent='octane'
)

simulator(
    atol=1e-16,
    rtol=1e-8,
)

model(
    toleranceKeepInEdge=1E-9,
    toleranceMoveToCore=0.001,
    toleranceInterruptSimulation=0.1,
    maximumEdgeSpecies=100000
)

options(
    units='si',
    saveRestartPeriod=None,
    drawMolecules=False,
    generatePlots=False,
    saveConcentrationProfiles=True,
)

<|next_version|>
# Data sources
database(
    thermoLibraries = ['primaryThermoLibrary'],
    reactionLibraries = [],
    seedMechanisms = [],
    kineticsDepositories = ['training'],
    kineticsFamilies = 'default',
    kineticsEstimator = 'rate rules',
)

# Constraints on generated species
generatedSpeciesConstraints(
    maximumRadicalElectrons = 3,
)

# List of species
species(
    label='octane',
    multiplicity = 1,
    reactive=True,
    structure=SMILES("C(CCCCC)CC"),
)

species(
    label='oxygen',
    multiplicity = 3,
    reactive=True,
    structure=SMILES("[O][O]"),
)

# Reaction systems
liquidReactor(
    temperature=(500,'K'),
    initialConcentrations={
        "octane": (6.154e-3,'mol/cm^3'),
        "oxygen": (4.953e-6,'mol/cm^3')
    },
    terminationTime=(5,'s'),
)

solvation(
	solvent='octane'
)

simulator(
    atol=1e-16,
    rtol=1e-8,
)

model(
    toleranceKeepInEdge=1E-9,
    toleranceMoveToCore=0.001,
    toleranceInterruptSimulation=0.1,
    maximumEdgeSpecies=100000
)

options(
    units='si',
    saveRestartPeriod=None,
    drawMolecules=False,
    generatePlots=False,
    saveConcentrationProfiles=True,
)


Add comments for tests of caching.

Add comments for tests of caching.

--- tests/chainer_tests/functions_tests/pooling_tests/test_pooling_nd_kernel.py
+++ tests/chainer_tests/functions_tests/pooling_tests/test_pooling_nd_kernel.py
@@ -24,6 +24,8 @@
             pooling_nd_kernel.PoolingNDKernelForward.generate(ndim)
             m.assert_called_once_with(ndim)
             pooling_nd_kernel.PoolingNDKernelForward.generate(ndim)
+            # Check that the mocked _generate() function is called just once
+            # because the result of generate() function is cached.
             m.assert_called_once_with(ndim)

     def test_pooling_nd_kernel_backward_memo(self):
@@ -33,6 +35,8 @@
             pooling_nd_kernel.PoolingNDKernelBackward.generate(ndim)
             m.assert_called_once_with(ndim)
             pooling_nd_kernel.PoolingNDKernelBackward.generate(ndim)
+            # Check that the mocked _generate() function is called just once
+            # because the result of generate() function is cached.
             m.assert_called_once_with(ndim)

<|original_code|>
import unittest

import mock

import chainer
from chainer.functions.pooling import pooling_nd_kernel
from chainer import testing
from chainer.testing import attr

@testing.parameterize(*testing.product({
    'ndim': [2, 3, 4],
}))
@attr.gpu
class TestPoolingNDKernelMemo(unittest.TestCase):

    def setUp(self):
        chainer.cuda.clear_memo()

    def test_pooling_nd_kernel_forward_memo(self):
        ndim = self.ndim
        with mock.patch('chainer.functions.pooling.pooling_nd_kernel.'
                        'PoolingNDKernelForward._generate') as m:
            pooling_nd_kernel.PoolingNDKernelForward.generate(ndim)
            m.assert_called_once_with(ndim)
            pooling_nd_kernel.PoolingNDKernelForward.generate(ndim)
            m.assert_called_once_with(ndim)

    def test_pooling_nd_kernel_backward_memo(self):
        ndim = self.ndim
        with mock.patch('chainer.functions.pooling.pooling_nd_kernel.'
                        'PoolingNDKernelBackward._generate') as m:
            pooling_nd_kernel.PoolingNDKernelBackward.generate(ndim)
            m.assert_called_once_with(ndim)
            pooling_nd_kernel.PoolingNDKernelBackward.generate(ndim)
            m.assert_called_once_with(ndim)

testing.run_module(__name__, __file__)

<|edits_diff|>
--- tests/chainer_tests/functions_tests/pooling_tests/test_pooling_nd_kernel.py
+++ tests/chainer_tests/functions_tests/pooling_tests/test_pooling_nd_kernel.py
@@ -24,6 +24,8 @@
             pooling_nd_kernel.PoolingNDKernelForward.generate(ndim)
             m.assert_called_once_with(ndim)
             pooling_nd_kernel.PoolingNDKernelForward.generate(ndim)
+            # Check that the mocked _generate() function is called just once
+            # because the result of generate() function is cached.
             m.assert_called_once_with(ndim)

     def test_pooling_nd_kernel_backward_memo(self):
<|current_version|>
import unittest

import mock

import chainer
from chainer.functions.pooling import pooling_nd_kernel
from chainer import testing
from chainer.testing import attr

@testing.parameterize(*testing.product({
    'ndim': [2, 3, 4],
}))
@attr.gpu
class TestPoolingNDKernelMemo(unittest.TestCase):

    def setUp(self):
        chainer.cuda.clear_memo()

    def test_pooling_nd_kernel_forward_memo(self):
        ndim = self.ndim
        with mock.patch('chainer.functions.pooling.pooling_nd_kernel.'
                        'PoolingNDKernelForward._generate') as m:
            pooling_nd_kernel.PoolingNDKernelForward.generate(ndim)
            m.assert_called_once_with(ndim)
            pooling_nd_kernel.PoolingNDKernelForward.generate(ndim)
            # Check that the mocked _generate() function is called just once
            # because the result of generate() function is cached.
            m.assert_called_once_with(ndim)

    def test_pooling_nd_kernel_backward_memo(self):
        ndim = self.ndim
        with mock.patch('chainer.functions.pooling.pooling_nd_kernel.'
                        'PoolingNDKernelBackward._generate') as m:
            pooling_nd_kernel.PoolingNDKernelBackward.generate(ndim)
            m.assert_called_once_with(ndim)
            pooling_nd_kernel.PoolingNDKernelBackward.generate(ndim)
            m.assert_called_once_with(ndim)

testing.run_module(__name__, __file__)

<|next_version|>
import unittest

import mock

import chainer
from chainer.functions.pooling import pooling_nd_kernel
from chainer import testing
from chainer.testing import attr

@testing.parameterize(*testing.product({
    'ndim': [2, 3, 4],
}))
@attr.gpu
class TestPoolingNDKernelMemo(unittest.TestCase):

    def setUp(self):
        chainer.cuda.clear_memo()

    def test_pooling_nd_kernel_forward_memo(self):
        ndim = self.ndim
        with mock.patch('chainer.functions.pooling.pooling_nd_kernel.'
                        'PoolingNDKernelForward._generate') as m:
            pooling_nd_kernel.PoolingNDKernelForward.generate(ndim)
            m.assert_called_once_with(ndim)
            pooling_nd_kernel.PoolingNDKernelForward.generate(ndim)
            # Check that the mocked _generate() function is called just once
            # because the result of generate() function is cached.
            m.assert_called_once_with(ndim)

    def test_pooling_nd_kernel_backward_memo(self):
        ndim = self.ndim
        with mock.patch('chainer.functions.pooling.pooling_nd_kernel.'
                        'PoolingNDKernelBackward._generate') as m:
            pooling_nd_kernel.PoolingNDKernelBackward.generate(ndim)
            m.assert_called_once_with(ndim)
            pooling_nd_kernel.PoolingNDKernelBackward.generate(ndim)
            # Check that the mocked _generate() function is called just once
            # because the result of generate() function is cached.
            m.assert_called_once_with(ndim)

testing.run_module(__name__, __file__)