{
    "file_diffs": [
        {
            "old_file_content": "# coding: utf-8\nfrom __future__ import absolute_import, division, print_function\nimport re\nimport sys\nimport datetime\n\nimport tornado.escape\nfrom tornado.escape import utf8\nfrom tornado.util import raise_exc_info, Configurable, exec_in, ArgReplacer, timedelta_to_seconds, import_object, re_unescape, is_finalizing, PY3\nfrom tornado.test.util import unittest\n\nif PY3:\n    from io import StringIO\nelse:\n    from cStringIO import StringIO\n\n\nclass RaiseExcInfoTest(unittest.TestCase):\n    def test_two_arg_exception(self):\n        # This test would fail on python 3 if raise_exc_info were simply\n        # a three-argument raise statement, because TwoArgException\n        # doesn't have a \"copy constructor\"\n        class TwoArgException(Exception):\n            def __init__(self, a, b):\n                super(TwoArgException, self).__init__()\n                self.a, self.b = a, b\n\n        try:\n            raise TwoArgException(1, 2)\n        except TwoArgException:\n            exc_info = sys.exc_info()\n        try:\n            raise_exc_info(exc_info)\n            self.fail(\"didn't get expected exception\")\n        except TwoArgException as e:\n            self.assertIs(e, exc_info[1])\n\n\nclass TestConfigurable(Configurable):\n    @classmethod\n    def configurable_base(cls):\n        return TestConfigurable\n\n    @classmethod\n    def configurable_default(cls):\n        return TestConfig1\n\n\nclass TestConfig1(TestConfigurable):\n    def initialize(self, pos_arg=None, a=None):\n        self.a = a\n        self.pos_arg = pos_arg\n\n\nclass TestConfig2(TestConfigurable):\n    def initialize(self, pos_arg=None, b=None):\n        self.b = b\n        self.pos_arg = pos_arg\n\n\nclass ConfigurableTest(unittest.TestCase):\n    def setUp(self):\n        self.saved = TestConfigurable._save_configuration()\n\n    def tearDown(self):\n        TestConfigurable._restore_configuration(self.saved)\n\n    def checkSubclasses(self):\n        # no matter how the class is configured, it should always be\n        # possible to instantiate the subclasses directly\n        self.assertIsInstance(TestConfig1(), TestConfig1)\n        self.assertIsInstance(TestConfig2(), TestConfig2)\n\n        obj = TestConfig1(a=1)\n        self.assertEqual(obj.a, 1)\n        obj = TestConfig2(b=2)\n        self.assertEqual(obj.b, 2)\n\n    def test_default(self):\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertIs(obj.a, None)\n\n        obj = TestConfigurable(a=1)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 1)\n\n        self.checkSubclasses()\n\n    def test_config_class(self):\n        TestConfigurable.configure(TestConfig2)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertIs(obj.b, None)\n\n        obj = TestConfigurable(b=2)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 2)\n\n        self.checkSubclasses()\n\n    def test_config_args(self):\n        TestConfigurable.configure(None, a=3)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 3)\n\n        obj = TestConfigurable(42, a=4)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 4)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig1()\n        self.assertIs(obj.a, None)\n\n    def test_config_class_args(self):\n        TestConfigurable.configure(TestConfig2, b=5)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 5)\n\n        obj = TestConfigurable(42, b=6)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 6)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig2()\n        self.assertIs(obj.b, None)\n\n\nclass UnicodeLiteralTest(unittest.TestCase):\n    def test_unicode_escapes(self):\n        self.assertEqual(utf8(u'\\u00e9'), b'\\xc3\\xa9')\n\n\nclass ExecInTest(unittest.TestCase):\n    # This test is python 2 only because there are no new future imports\n    # defined in python 3 yet.\n    @unittest.skipIf(sys.version_info >= print_function.getMandatoryRelease(),\n                     'no testable future imports')\n    def test_no_inherit_future(self):\n        # This file has from __future__ import print_function...\n        f = StringIO()\n        print('hello', file=f)\n        # ...but the template doesn't\n        exec_in('print >> f, \"world\"', dict(f=f))\n        self.assertEqual(f.getvalue(), 'hello\\nworld\\n')\n\n\nclass ArgReplacerTest(unittest.TestCase):\n    def setUp(self):\n        def function(x, y, callback=None, z=None):\n            pass\n        self.replacer = ArgReplacer(function, 'callback')\n\n    def test_omitted(self):\n        args = (1, 2)\n        kwargs = dict()\n        self.assertIs(self.replacer.get_old_value(args, kwargs), None)\n        self.assertEqual(self.replacer.replace('new', args, kwargs),\n                         (None, (1, 2), dict(callback='new')))\n\n    def test_position(self):\n        args = (1, 2, 'old', 3)\n        kwargs = dict()\n        self.assertEqual(self.replacer.get_old_value(args, kwargs), 'old')\n        self.assertEqual(self.replacer.replace('new', args, kwargs),\n                         ('old', [1, 2, 'new', 3], dict()))\n\n    def test_keyword(self):\n        args = (1,)\n        kwargs = dict(y=2, callback='old', z=3)\n        self.assertEqual(self.replacer.get_old_value(args, kwargs), 'old')\n        self.assertEqual(self.replacer.replace('new', args, kwargs),\n                         ('old', (1,), dict(y=2, callback='new', z=3)))\n\n\nclass TimedeltaToSecondsTest(unittest.TestCase):\n    def test_timedelta_to_seconds(self):\n        time_delta = datetime.timedelta(hours=1)\n        self.assertEqual(timedelta_to_seconds(time_delta), 3600.0)\n\n\nclass ImportObjectTest(unittest.TestCase):\n    def test_import_member(self):\n        self.assertIs(import_object('tornado.escape.utf8'), utf8)\n\n    def test_import_member_unicode(self):\n        self.assertIs(import_object(u'tornado.escape.utf8'), utf8)\n\n    def test_import_module(self):\n        self.assertIs(import_object('tornado.escape'), tornado.escape)\n\n    def test_import_module_unicode(self):\n        # The internal implementation of __import__ differs depending on\n        # whether the thing being imported is a module or not.\n        # This variant requires a byte string in python 2.\n        self.assertIs(import_object(u'tornado.escape'), tornado.escape)\n\n\nclass ReUnescapeTest(unittest.TestCase):\n    def test_re_unescape(self):\n        test_strings = (\n            '/favicon.ico',\n            'index.html',\n            'Hello, World!',\n            '!$@#%;',\n        )\n        for string in test_strings:\n            self.assertEqual(string, re_unescape(re.escape(string)))\n\n    def test_re_unescape_raises_error_on_invalid_input(self):\n        with self.assertRaises(ValueError):\n            re_unescape('\\\\d')\n        with self.assertRaises(ValueError):\n            re_unescape('\\\\b')\n        with self.assertRaises(ValueError):\n            re_unescape('\\\\Z')\n\n\nclass IsFinalizingTest(unittest.TestCase):\n    def test_basic(self):\n        self.assertFalse(is_finalizing())\n",
            "new_file_content": "# coding: utf-8\nfrom __future__ import absolute_import, division, print_function\nimport re\nimport sys\nimport datetime\n\nimport tornado.escape\nfrom tornado.escape import utf8\nfrom tornado.util import raise_exc_info, Configurable, exec_in, ArgReplacer, timedelta_to_seconds, import_object, re_unescape, is_finalizing, PY3\nfrom tornado.test.util import unittest\n\nif PY3:\n    from io import StringIO\nelse:\n    from cStringIO import StringIO\n\n\nclass RaiseExcInfoTest(unittest.TestCase):\n    def test_two_arg_exception(self):\n        # This test would fail on python 3 if raise_exc_info were simply\n        # a three-argument raise statement, because TwoArgException\n        # doesn't have a \"copy constructor\"\n        class TwoArgException(Exception):\n            def __init__(self, a, b):\n                super(TwoArgException, self).__init__()\n                self.a, self.b = a, b\n\n        try:\n            raise TwoArgException(1, 2)\n        except TwoArgException:\n            exc_info = sys.exc_info()\n        try:\n            raise_exc_info(exc_info)\n            self.fail(\"didn't get expected exception\")\n        except TwoArgException as e:\n            self.assertIs(e, exc_info[1])\n\n\nclass TestConfigurable(Configurable):\n    @classmethod\n    def configurable_base(cls):\n        return TestConfigurable\n\n    @classmethod\n    def configurable_default(cls):\n        return TestConfig1\n\n\nclass TestConfig1(TestConfigurable):\n    def initialize(self, pos_arg=None, a=None):\n        self.a = a\n        self.pos_arg = pos_arg\n\n\nclass TestConfig2(TestConfigurable):\n    def initialize(self, pos_arg=None, b=None):\n        self.b = b\n        self.pos_arg = pos_arg\n\n\nclass TestConfig3(TestConfigurable):\n    # TestConfig3 is a configuration option that is itself configurable.\n    @classmethod\n    def configurable_base(cls):\n        return TestConfig3\n\n    @classmethod\n    def configurable_default(cls):\n        return TestConfig3A\n\n\nclass TestConfig3A(TestConfig3):\n    def initialize(self, a=None):\n        self.a = a\n\n\nclass TestConfig3B(TestConfig3):\n    def initialize(self, b=None):\n        self.b = b\n\n\nclass ConfigurableTest(unittest.TestCase):\n    def setUp(self):\n        self.saved = TestConfigurable._save_configuration()\n        self.saved3 = TestConfig3._save_configuration()\n\n    def tearDown(self):\n        TestConfigurable._restore_configuration(self.saved)\n        TestConfig3._restore_configuration(self.saved3)\n\n    def checkSubclasses(self):\n        # no matter how the class is configured, it should always be\n        # possible to instantiate the subclasses directly\n        self.assertIsInstance(TestConfig1(), TestConfig1)\n        self.assertIsInstance(TestConfig2(), TestConfig2)\n\n        obj = TestConfig1(a=1)\n        self.assertEqual(obj.a, 1)\n        obj = TestConfig2(b=2)\n        self.assertEqual(obj.b, 2)\n\n    def test_default(self):\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertIs(obj.a, None)\n\n        obj = TestConfigurable(a=1)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 1)\n\n        self.checkSubclasses()\n\n    def test_config_class(self):\n        TestConfigurable.configure(TestConfig2)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertIs(obj.b, None)\n\n        obj = TestConfigurable(b=2)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 2)\n\n        self.checkSubclasses()\n\n    def test_config_args(self):\n        TestConfigurable.configure(None, a=3)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 3)\n\n        obj = TestConfigurable(42, a=4)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 4)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig1()\n        self.assertIs(obj.a, None)\n\n    def test_config_class_args(self):\n        TestConfigurable.configure(TestConfig2, b=5)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 5)\n\n        obj = TestConfigurable(42, b=6)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 6)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig2()\n        self.assertIs(obj.b, None)\n\n    def test_config_multi_level(self):\n        TestConfigurable.configure(TestConfig3, a=1)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig3A)\n        self.assertEqual(obj.a, 1)\n\n        TestConfigurable.configure(TestConfig3)\n        TestConfig3.configure(TestConfig3B, b=2)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig3B)\n        self.assertEqual(obj.b, 2)\n\n    def test_config_inner_level(self):\n        # The inner level can be used even when the outer level\n        # doesn't point to it.\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3A)\n\n        TestConfig3.configure(TestConfig3B)\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3B)\n\n        # Configuring the base doesn't configure the inner.\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        TestConfigurable.configure(TestConfig2)\n\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3B)\n\n\nclass UnicodeLiteralTest(unittest.TestCase):\n    def test_unicode_escapes(self):\n        self.assertEqual(utf8(u'\\u00e9'), b'\\xc3\\xa9')\n\n\nclass ExecInTest(unittest.TestCase):\n    # This test is python 2 only because there are no new future imports\n    # defined in python 3 yet.\n    @unittest.skipIf(sys.version_info >= print_function.getMandatoryRelease(),\n                     'no testable future imports')\n    def test_no_inherit_future(self):\n        # This file has from __future__ import print_function...\n        f = StringIO()\n        print('hello', file=f)\n        # ...but the template doesn't\n        exec_in('print >> f, \"world\"', dict(f=f))\n        self.assertEqual(f.getvalue(), 'hello\\nworld\\n')\n\n\nclass ArgReplacerTest(unittest.TestCase):\n    def setUp(self):\n        def function(x, y, callback=None, z=None):\n            pass\n        self.replacer = ArgReplacer(function, 'callback')\n\n    def test_omitted(self):\n        args = (1, 2)\n        kwargs = dict()\n        self.assertIs(self.replacer.get_old_value(args, kwargs), None)\n        self.assertEqual(self.replacer.replace('new', args, kwargs),\n                         (None, (1, 2), dict(callback='new')))\n\n    def test_position(self):\n        args = (1, 2, 'old', 3)\n        kwargs = dict()\n        self.assertEqual(self.replacer.get_old_value(args, kwargs), 'old')\n        self.assertEqual(self.replacer.replace('new', args, kwargs),\n                         ('old', [1, 2, 'new', 3], dict()))\n\n    def test_keyword(self):\n        args = (1,)\n        kwargs = dict(y=2, callback='old', z=3)\n        self.assertEqual(self.replacer.get_old_value(args, kwargs), 'old')\n        self.assertEqual(self.replacer.replace('new', args, kwargs),\n                         ('old', (1,), dict(y=2, callback='new', z=3)))\n\n\nclass TimedeltaToSecondsTest(unittest.TestCase):\n    def test_timedelta_to_seconds(self):\n        time_delta = datetime.timedelta(hours=1)\n        self.assertEqual(timedelta_to_seconds(time_delta), 3600.0)\n\n\nclass ImportObjectTest(unittest.TestCase):\n    def test_import_member(self):\n        self.assertIs(import_object('tornado.escape.utf8'), utf8)\n\n    def test_import_member_unicode(self):\n        self.assertIs(import_object(u'tornado.escape.utf8'), utf8)\n\n    def test_import_module(self):\n        self.assertIs(import_object('tornado.escape'), tornado.escape)\n\n    def test_import_module_unicode(self):\n        # The internal implementation of __import__ differs depending on\n        # whether the thing being imported is a module or not.\n        # This variant requires a byte string in python 2.\n        self.assertIs(import_object(u'tornado.escape'), tornado.escape)\n\n\nclass ReUnescapeTest(unittest.TestCase):\n    def test_re_unescape(self):\n        test_strings = (\n            '/favicon.ico',\n            'index.html',\n            'Hello, World!',\n            '!$@#%;',\n        )\n        for string in test_strings:\n            self.assertEqual(string, re_unescape(re.escape(string)))\n\n    def test_re_unescape_raises_error_on_invalid_input(self):\n        with self.assertRaises(ValueError):\n            re_unescape('\\\\d')\n        with self.assertRaises(ValueError):\n            re_unescape('\\\\b')\n        with self.assertRaises(ValueError):\n            re_unescape('\\\\Z')\n\n\nclass IsFinalizingTest(unittest.TestCase):\n    def test_basic(self):\n        self.assertFalse(is_finalizing())\n",
            "header": {
                "file": {
                    "path": "tornado/test/util_test.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "459cb9c3",
                "new_commit_hash": "48924d44",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/test/util_test.py"
            },
            "plus_file": {
                "path": "b/tornado/test/util_test.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 58,
                            "length": 12
                        },
                        "new_range": {
                            "start": 58,
                            "length": 35
                        },
                        "section": "class TestConfig2(TestConfigurable):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        self.pos_arg = pos_arg",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "class TestConfig3(TestConfigurable):",
                                "type": "added"
                            },
                            {
                                "content": "    # TestConfig3 is a configuration option that is itself configurable.",
                                "type": "added"
                            },
                            {
                                "content": "    @classmethod",
                                "type": "added"
                            },
                            {
                                "content": "    def configurable_base(cls):",
                                "type": "added"
                            },
                            {
                                "content": "        return TestConfig3",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    @classmethod",
                                "type": "added"
                            },
                            {
                                "content": "    def configurable_default(cls):",
                                "type": "added"
                            },
                            {
                                "content": "        return TestConfig3A",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "class TestConfig3A(TestConfig3):",
                                "type": "added"
                            },
                            {
                                "content": "    def initialize(self, a=None):",
                                "type": "added"
                            },
                            {
                                "content": "        self.a = a",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "class TestConfig3B(TestConfig3):",
                                "type": "added"
                            },
                            {
                                "content": "    def initialize(self, b=None):",
                                "type": "added"
                            },
                            {
                                "content": "        self.b = b",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "class ConfigurableTest(unittest.TestCase):",
                                "type": "context"
                            },
                            {
                                "content": "    def setUp(self):",
                                "type": "context"
                            },
                            {
                                "content": "        self.saved = TestConfigurable._save_configuration()",
                                "type": "context"
                            },
                            {
                                "content": "        self.saved3 = TestConfig3._save_configuration()",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def tearDown(self):",
                                "type": "context"
                            },
                            {
                                "content": "        TestConfigurable._restore_configuration(self.saved)",
                                "type": "context"
                            },
                            {
                                "content": "        TestConfig3._restore_configuration(self.saved3)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def checkSubclasses(self):",
                                "type": "context"
                            },
                            {
                                "content": "        # no matter how the class is configured, it should always be",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/test/util_test.py",
                            "type": "method",
                            "name": "ConfigurableTest.setUp",
                            "content": "class ConfigurableTest(unittest.TestCase):\n    def setUp(self):\n        self.saved = TestConfigurable._save_configuration()\n        self.saved3 = TestConfig3._save_configuration()\n\n    def tearDown(self):\n        TestConfigurable._restore_configuration(self.saved)\n        TestConfig3._restore_configuration(self.saved3)\n\n    def checkSubclasses(self):\n        # no matter how the class is configured, it should always be\n        # possible to instantiate the subclasses directly\n        self.assertIsInstance(TestConfig1(), TestConfig1)\n        self.assertIsInstance(TestConfig2(), TestConfig2)\n\n        obj = TestConfig1(a=1)\n        self.assertEqual(obj.a, 1)\n        obj = TestConfig2(b=2)\n        self.assertEqual(obj.b, 2)\n\n    def test_default(self):\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertIs(obj.a, None)\n\n        obj = TestConfigurable(a=1)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 1)\n\n        self.checkSubclasses()\n\n    def test_config_class(self):\n        TestConfigurable.configure(TestConfig2)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertIs(obj.b, None)\n\n        obj = TestConfigurable(b=2)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 2)\n\n        self.checkSubclasses()\n\n    def test_config_args(self):\n        TestConfigurable.configure(None, a=3)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 3)\n\n        obj = TestConfigurable(42, a=4)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 4)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig1()\n        self.assertIs(obj.a, None)\n\n    def test_config_class_args(self):\n        TestConfigurable.configure(TestConfig2, b=5)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 5)\n\n        obj = TestConfigurable(42, b=6)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 6)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig2()\n        self.assertIs(obj.b, None)\n\n    def test_config_multi_level(self):\n        TestConfigurable.configure(TestConfig3, a=1)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig3A)\n        self.assertEqual(obj.a, 1)\n\n        TestConfigurable.configure(TestConfig3)\n        TestConfig3.configure(TestConfig3B, b=2)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig3B)\n        self.assertEqual(obj.b, 2)\n\n    def test_config_inner_level(self):\n        # The inner level can be used even when the outer level\n        # doesn't point to it.\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3A)\n\n        TestConfig3.configure(TestConfig3B)\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3B)\n\n        # Configuring the base doesn't configure the inner.\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        TestConfigurable.configure(TestConfig2)\n\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3B)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 83,
                            "end_lineno": 85,
                            "parent": {
                                "file_name": "tornado/test/util_test.py",
                                "type": "class",
                                "name": "ConfigurableTest",
                                "content": "class ConfigurableTest(unittest.TestCase):\n    def setUp(self):\n        self.saved = TestConfigurable._save_configuration()\n        self.saved3 = TestConfig3._save_configuration()\n\n    def tearDown(self):\n        TestConfigurable._restore_configuration(self.saved)\n        TestConfig3._restore_configuration(self.saved3)\n\n    def checkSubclasses(self):\n        # no matter how the class is configured, it should always be\n        # possible to instantiate the subclasses directly\n        self.assertIsInstance(TestConfig1(), TestConfig1)\n        self.assertIsInstance(TestConfig2(), TestConfig2)\n\n        obj = TestConfig1(a=1)\n        self.assertEqual(obj.a, 1)\n        obj = TestConfig2(b=2)\n        self.assertEqual(obj.b, 2)\n\n    def test_default(self):\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertIs(obj.a, None)\n\n        obj = TestConfigurable(a=1)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 1)\n\n        self.checkSubclasses()\n\n    def test_config_class(self):\n        TestConfigurable.configure(TestConfig2)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertIs(obj.b, None)\n\n        obj = TestConfigurable(b=2)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 2)\n\n        self.checkSubclasses()\n\n    def test_config_args(self):\n        TestConfigurable.configure(None, a=3)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 3)\n\n        obj = TestConfigurable(42, a=4)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 4)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig1()\n        self.assertIs(obj.a, None)\n\n    def test_config_class_args(self):\n        TestConfigurable.configure(TestConfig2, b=5)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 5)\n\n        obj = TestConfigurable(42, b=6)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 6)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig2()\n        self.assertIs(obj.b, None)\n\n    def test_config_multi_level(self):\n        TestConfigurable.configure(TestConfig3, a=1)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig3A)\n        self.assertEqual(obj.a, 1)\n\n        TestConfigurable.configure(TestConfig3)\n        TestConfig3.configure(TestConfig3B, b=2)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig3B)\n        self.assertEqual(obj.b, 2)\n\n    def test_config_inner_level(self):\n        # The inner level can be used even when the outer level\n        # doesn't point to it.\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3A)\n\n        TestConfig3.configure(TestConfig3B)\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3B)\n\n        # Configuring the base doesn't configure the inner.\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        TestConfigurable.configure(TestConfig2)\n\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3B)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 82,
                                "end_lineno": 188,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/util_test.py",
                            "type": "class",
                            "name": "ConfigurableTest",
                            "content": "class ConfigurableTest(unittest.TestCase):\n    def setUp(self):\n        self.saved = TestConfigurable._save_configuration()\n        self.saved3 = TestConfig3._save_configuration()\n\n    def tearDown(self):\n        TestConfigurable._restore_configuration(self.saved)\n        TestConfig3._restore_configuration(self.saved3)\n\n    def checkSubclasses(self):\n        # no matter how the class is configured, it should always be\n        # possible to instantiate the subclasses directly\n        self.assertIsInstance(TestConfig1(), TestConfig1)\n        self.assertIsInstance(TestConfig2(), TestConfig2)\n\n        obj = TestConfig1(a=1)\n        self.assertEqual(obj.a, 1)\n        obj = TestConfig2(b=2)\n        self.assertEqual(obj.b, 2)\n\n    def test_default(self):\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertIs(obj.a, None)\n\n        obj = TestConfigurable(a=1)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 1)\n\n        self.checkSubclasses()\n\n    def test_config_class(self):\n        TestConfigurable.configure(TestConfig2)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertIs(obj.b, None)\n\n        obj = TestConfigurable(b=2)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 2)\n\n        self.checkSubclasses()\n\n    def test_config_args(self):\n        TestConfigurable.configure(None, a=3)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 3)\n\n        obj = TestConfigurable(42, a=4)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 4)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig1()\n        self.assertIs(obj.a, None)\n\n    def test_config_class_args(self):\n        TestConfigurable.configure(TestConfig2, b=5)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 5)\n\n        obj = TestConfigurable(42, b=6)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 6)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig2()\n        self.assertIs(obj.b, None)\n\n    def test_config_multi_level(self):\n        TestConfigurable.configure(TestConfig3, a=1)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig3A)\n        self.assertEqual(obj.a, 1)\n\n        TestConfigurable.configure(TestConfig3)\n        TestConfig3.configure(TestConfig3B, b=2)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig3B)\n        self.assertEqual(obj.b, 2)\n\n    def test_config_inner_level(self):\n        # The inner level can be used even when the outer level\n        # doesn't point to it.\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3A)\n\n        TestConfig3.configure(TestConfig3B)\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3B)\n\n        # Configuring the base doesn't configure the inner.\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        TestConfigurable.configure(TestConfig2)\n\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3B)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 82,
                            "end_lineno": 188,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/test/util_test.py",
                            "type": "method",
                            "name": "ConfigurableTest.tearDown",
                            "content": "class ConfigurableTest(unittest.TestCase):\n    def setUp(self):\n        self.saved = TestConfigurable._save_configuration()\n        self.saved3 = TestConfig3._save_configuration()\n\n    def tearDown(self):\n        TestConfigurable._restore_configuration(self.saved)\n        TestConfig3._restore_configuration(self.saved3)\n\n    def checkSubclasses(self):\n        # no matter how the class is configured, it should always be\n        # possible to instantiate the subclasses directly\n        self.assertIsInstance(TestConfig1(), TestConfig1)\n        self.assertIsInstance(TestConfig2(), TestConfig2)\n\n        obj = TestConfig1(a=1)\n        self.assertEqual(obj.a, 1)\n        obj = TestConfig2(b=2)\n        self.assertEqual(obj.b, 2)\n\n    def test_default(self):\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertIs(obj.a, None)\n\n        obj = TestConfigurable(a=1)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 1)\n\n        self.checkSubclasses()\n\n    def test_config_class(self):\n        TestConfigurable.configure(TestConfig2)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertIs(obj.b, None)\n\n        obj = TestConfigurable(b=2)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 2)\n\n        self.checkSubclasses()\n\n    def test_config_args(self):\n        TestConfigurable.configure(None, a=3)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 3)\n\n        obj = TestConfigurable(42, a=4)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 4)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig1()\n        self.assertIs(obj.a, None)\n\n    def test_config_class_args(self):\n        TestConfigurable.configure(TestConfig2, b=5)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 5)\n\n        obj = TestConfigurable(42, b=6)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 6)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig2()\n        self.assertIs(obj.b, None)\n\n    def test_config_multi_level(self):\n        TestConfigurable.configure(TestConfig3, a=1)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig3A)\n        self.assertEqual(obj.a, 1)\n\n        TestConfigurable.configure(TestConfig3)\n        TestConfig3.configure(TestConfig3B, b=2)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig3B)\n        self.assertEqual(obj.b, 2)\n\n    def test_config_inner_level(self):\n        # The inner level can be used even when the outer level\n        # doesn't point to it.\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3A)\n\n        TestConfig3.configure(TestConfig3B)\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3B)\n\n        # Configuring the base doesn't configure the inner.\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        TestConfigurable.configure(TestConfig2)\n\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3B)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 87,
                            "end_lineno": 89,
                            "parent": {
                                "file_name": "tornado/test/util_test.py",
                                "type": "class",
                                "name": "ConfigurableTest",
                                "content": "class ConfigurableTest(unittest.TestCase):\n    def setUp(self):\n        self.saved = TestConfigurable._save_configuration()\n        self.saved3 = TestConfig3._save_configuration()\n\n    def tearDown(self):\n        TestConfigurable._restore_configuration(self.saved)\n        TestConfig3._restore_configuration(self.saved3)\n\n    def checkSubclasses(self):\n        # no matter how the class is configured, it should always be\n        # possible to instantiate the subclasses directly\n        self.assertIsInstance(TestConfig1(), TestConfig1)\n        self.assertIsInstance(TestConfig2(), TestConfig2)\n\n        obj = TestConfig1(a=1)\n        self.assertEqual(obj.a, 1)\n        obj = TestConfig2(b=2)\n        self.assertEqual(obj.b, 2)\n\n    def test_default(self):\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertIs(obj.a, None)\n\n        obj = TestConfigurable(a=1)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 1)\n\n        self.checkSubclasses()\n\n    def test_config_class(self):\n        TestConfigurable.configure(TestConfig2)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertIs(obj.b, None)\n\n        obj = TestConfigurable(b=2)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 2)\n\n        self.checkSubclasses()\n\n    def test_config_args(self):\n        TestConfigurable.configure(None, a=3)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 3)\n\n        obj = TestConfigurable(42, a=4)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 4)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig1()\n        self.assertIs(obj.a, None)\n\n    def test_config_class_args(self):\n        TestConfigurable.configure(TestConfig2, b=5)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 5)\n\n        obj = TestConfigurable(42, b=6)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 6)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig2()\n        self.assertIs(obj.b, None)\n\n    def test_config_multi_level(self):\n        TestConfigurable.configure(TestConfig3, a=1)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig3A)\n        self.assertEqual(obj.a, 1)\n\n        TestConfigurable.configure(TestConfig3)\n        TestConfig3.configure(TestConfig3B, b=2)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig3B)\n        self.assertEqual(obj.b, 2)\n\n    def test_config_inner_level(self):\n        # The inner level can be used even when the outer level\n        # doesn't point to it.\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3A)\n\n        TestConfig3.configure(TestConfig3B)\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3B)\n\n        # Configuring the base doesn't configure the inner.\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        TestConfigurable.configure(TestConfig2)\n\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3B)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 82,
                                "end_lineno": 188,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/util_test.py",
                            "type": "class",
                            "name": "TestConfig3",
                            "content": "class TestConfig3(TestConfigurable):\n    # TestConfig3 is a configuration option that is itself configurable.\n    @classmethod\n    def configurable_base(cls):\n        return TestConfig3\n\n    @classmethod\n    def configurable_default(cls):\n        return TestConfig3A",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 61,
                            "end_lineno": 69,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/test/util_test.py",
                            "type": "method",
                            "name": "TestConfig3.configurable_base",
                            "content": "class TestConfig3(TestConfigurable):\n    # TestConfig3 is a configuration option that is itself configurable.\n    @classmethod\n    def configurable_base(cls):\n        return TestConfig3\n\n    @classmethod\n    def configurable_default(cls):\n        return TestConfig3A",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 64,
                            "end_lineno": 65,
                            "parent": {
                                "file_name": "tornado/test/util_test.py",
                                "type": "class",
                                "name": "TestConfig3",
                                "content": "class TestConfig3(TestConfigurable):\n    # TestConfig3 is a configuration option that is itself configurable.\n    @classmethod\n    def configurable_base(cls):\n        return TestConfig3\n\n    @classmethod\n    def configurable_default(cls):\n        return TestConfig3A",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 61,
                                "end_lineno": 69,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/util_test.py",
                            "type": "class",
                            "name": "TestConfig3A",
                            "content": "class TestConfig3A(TestConfig3):\n    def initialize(self, a=None):\n        self.a = a",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 72,
                            "end_lineno": 74,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/test/util_test.py",
                            "type": "method",
                            "name": "TestConfig3.configurable_default",
                            "content": "class TestConfig3(TestConfigurable):\n    # TestConfig3 is a configuration option that is itself configurable.\n    @classmethod\n    def configurable_base(cls):\n        return TestConfig3\n\n    @classmethod\n    def configurable_default(cls):\n        return TestConfig3A",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 68,
                            "end_lineno": 69,
                            "parent": {
                                "file_name": "tornado/test/util_test.py",
                                "type": "class",
                                "name": "TestConfig3",
                                "content": "class TestConfig3(TestConfigurable):\n    # TestConfig3 is a configuration option that is itself configurable.\n    @classmethod\n    def configurable_base(cls):\n        return TestConfig3\n\n    @classmethod\n    def configurable_default(cls):\n        return TestConfig3A",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 61,
                                "end_lineno": 69,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/util_test.py",
                            "type": "class",
                            "name": "TestConfig3B",
                            "content": "class TestConfig3B(TestConfig3):\n    def initialize(self, b=None):\n        self.b = b",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 77,
                            "end_lineno": 79,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/test/util_test.py",
                            "type": "method",
                            "name": "TestConfig3A.initialize",
                            "content": "class TestConfig3A(TestConfig3):\n    def initialize(self, a=None):\n        self.a = a",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 73,
                            "end_lineno": 74,
                            "parent": {
                                "file_name": "tornado/test/util_test.py",
                                "type": "class",
                                "name": "TestConfig3A",
                                "content": "class TestConfig3A(TestConfig3):\n    def initialize(self, a=None):\n        self.a = a",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 72,
                                "end_lineno": 74,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/util_test.py",
                            "type": "method",
                            "name": "TestConfig3B.initialize",
                            "content": "class TestConfig3B(TestConfig3):\n    def initialize(self, b=None):\n        self.b = b",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 78,
                            "end_lineno": 79,
                            "parent": {
                                "file_name": "tornado/test/util_test.py",
                                "type": "class",
                                "name": "TestConfig3B",
                                "content": "class TestConfig3B(TestConfig3):\n    def initialize(self, b=None):\n        self.b = b",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 77,
                                "end_lineno": 79,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 131,
                            "length": 6
                        },
                        "new_range": {
                            "start": 154,
                            "length": 39
                        },
                        "section": "class ConfigurableTest(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        obj = TestConfig2()",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertIs(obj.b, None)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def test_config_multi_level(self):",
                                "type": "added"
                            },
                            {
                                "content": "        TestConfigurable.configure(TestConfig3, a=1)",
                                "type": "added"
                            },
                            {
                                "content": "        obj = TestConfigurable()",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertIsInstance(obj, TestConfig3A)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(obj.a, 1)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        TestConfigurable.configure(TestConfig3)",
                                "type": "added"
                            },
                            {
                                "content": "        TestConfig3.configure(TestConfig3B, b=2)",
                                "type": "added"
                            },
                            {
                                "content": "        obj = TestConfigurable()",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertIsInstance(obj, TestConfig3B)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertEqual(obj.b, 2)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_config_inner_level(self):",
                                "type": "added"
                            },
                            {
                                "content": "        # The inner level can be used even when the outer level",
                                "type": "added"
                            },
                            {
                                "content": "        # doesn't point to it.",
                                "type": "added"
                            },
                            {
                                "content": "        obj = TestConfig3()",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertIsInstance(obj, TestConfig3A)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        TestConfig3.configure(TestConfig3B)",
                                "type": "added"
                            },
                            {
                                "content": "        obj = TestConfig3()",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertIsInstance(obj, TestConfig3B)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        # Configuring the base doesn't configure the inner.",
                                "type": "added"
                            },
                            {
                                "content": "        obj = TestConfigurable()",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertIsInstance(obj, TestConfig1)",
                                "type": "added"
                            },
                            {
                                "content": "        TestConfigurable.configure(TestConfig2)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        obj = TestConfigurable()",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertIsInstance(obj, TestConfig2)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        obj = TestConfig3()",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertIsInstance(obj, TestConfig3B)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "class UnicodeLiteralTest(unittest.TestCase):",
                                "type": "context"
                            },
                            {
                                "content": "    def test_unicode_escapes(self):",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/test/util_test.py",
                            "type": "class",
                            "name": "ConfigurableTest",
                            "content": "class ConfigurableTest(unittest.TestCase):\n    def setUp(self):\n        self.saved = TestConfigurable._save_configuration()\n        self.saved3 = TestConfig3._save_configuration()\n\n    def tearDown(self):\n        TestConfigurable._restore_configuration(self.saved)\n        TestConfig3._restore_configuration(self.saved3)\n\n    def checkSubclasses(self):\n        # no matter how the class is configured, it should always be\n        # possible to instantiate the subclasses directly\n        self.assertIsInstance(TestConfig1(), TestConfig1)\n        self.assertIsInstance(TestConfig2(), TestConfig2)\n\n        obj = TestConfig1(a=1)\n        self.assertEqual(obj.a, 1)\n        obj = TestConfig2(b=2)\n        self.assertEqual(obj.b, 2)\n\n    def test_default(self):\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertIs(obj.a, None)\n\n        obj = TestConfigurable(a=1)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 1)\n\n        self.checkSubclasses()\n\n    def test_config_class(self):\n        TestConfigurable.configure(TestConfig2)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertIs(obj.b, None)\n\n        obj = TestConfigurable(b=2)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 2)\n\n        self.checkSubclasses()\n\n    def test_config_args(self):\n        TestConfigurable.configure(None, a=3)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 3)\n\n        obj = TestConfigurable(42, a=4)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 4)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig1()\n        self.assertIs(obj.a, None)\n\n    def test_config_class_args(self):\n        TestConfigurable.configure(TestConfig2, b=5)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 5)\n\n        obj = TestConfigurable(42, b=6)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 6)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig2()\n        self.assertIs(obj.b, None)\n\n    def test_config_multi_level(self):\n        TestConfigurable.configure(TestConfig3, a=1)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig3A)\n        self.assertEqual(obj.a, 1)\n\n        TestConfigurable.configure(TestConfig3)\n        TestConfig3.configure(TestConfig3B, b=2)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig3B)\n        self.assertEqual(obj.b, 2)\n\n    def test_config_inner_level(self):\n        # The inner level can be used even when the outer level\n        # doesn't point to it.\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3A)\n\n        TestConfig3.configure(TestConfig3B)\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3B)\n\n        # Configuring the base doesn't configure the inner.\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        TestConfigurable.configure(TestConfig2)\n\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3B)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 82,
                            "end_lineno": 188,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/util_test.py",
                            "type": "method",
                            "name": "ConfigurableTest.test_config_inner_level",
                            "content": "class ConfigurableTest(unittest.TestCase):\n    def setUp(self):\n        self.saved = TestConfigurable._save_configuration()\n        self.saved3 = TestConfig3._save_configuration()\n\n    def tearDown(self):\n        TestConfigurable._restore_configuration(self.saved)\n        TestConfig3._restore_configuration(self.saved3)\n\n    def checkSubclasses(self):\n        # no matter how the class is configured, it should always be\n        # possible to instantiate the subclasses directly\n        self.assertIsInstance(TestConfig1(), TestConfig1)\n        self.assertIsInstance(TestConfig2(), TestConfig2)\n\n        obj = TestConfig1(a=1)\n        self.assertEqual(obj.a, 1)\n        obj = TestConfig2(b=2)\n        self.assertEqual(obj.b, 2)\n\n    def test_default(self):\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertIs(obj.a, None)\n\n        obj = TestConfigurable(a=1)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 1)\n\n        self.checkSubclasses()\n\n    def test_config_class(self):\n        TestConfigurable.configure(TestConfig2)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertIs(obj.b, None)\n\n        obj = TestConfigurable(b=2)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 2)\n\n        self.checkSubclasses()\n\n    def test_config_args(self):\n        TestConfigurable.configure(None, a=3)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 3)\n\n        obj = TestConfigurable(42, a=4)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 4)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig1()\n        self.assertIs(obj.a, None)\n\n    def test_config_class_args(self):\n        TestConfigurable.configure(TestConfig2, b=5)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 5)\n\n        obj = TestConfigurable(42, b=6)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 6)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig2()\n        self.assertIs(obj.b, None)\n\n    def test_config_multi_level(self):\n        TestConfigurable.configure(TestConfig3, a=1)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig3A)\n        self.assertEqual(obj.a, 1)\n\n        TestConfigurable.configure(TestConfig3)\n        TestConfig3.configure(TestConfig3B, b=2)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig3B)\n        self.assertEqual(obj.b, 2)\n\n    def test_config_inner_level(self):\n        # The inner level can be used even when the outer level\n        # doesn't point to it.\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3A)\n\n        TestConfig3.configure(TestConfig3B)\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3B)\n\n        # Configuring the base doesn't configure the inner.\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        TestConfigurable.configure(TestConfig2)\n\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3B)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 169,
                            "end_lineno": 188,
                            "parent": {
                                "file_name": "tornado/test/util_test.py",
                                "type": "class",
                                "name": "ConfigurableTest",
                                "content": "class ConfigurableTest(unittest.TestCase):\n    def setUp(self):\n        self.saved = TestConfigurable._save_configuration()\n        self.saved3 = TestConfig3._save_configuration()\n\n    def tearDown(self):\n        TestConfigurable._restore_configuration(self.saved)\n        TestConfig3._restore_configuration(self.saved3)\n\n    def checkSubclasses(self):\n        # no matter how the class is configured, it should always be\n        # possible to instantiate the subclasses directly\n        self.assertIsInstance(TestConfig1(), TestConfig1)\n        self.assertIsInstance(TestConfig2(), TestConfig2)\n\n        obj = TestConfig1(a=1)\n        self.assertEqual(obj.a, 1)\n        obj = TestConfig2(b=2)\n        self.assertEqual(obj.b, 2)\n\n    def test_default(self):\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertIs(obj.a, None)\n\n        obj = TestConfigurable(a=1)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 1)\n\n        self.checkSubclasses()\n\n    def test_config_class(self):\n        TestConfigurable.configure(TestConfig2)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertIs(obj.b, None)\n\n        obj = TestConfigurable(b=2)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 2)\n\n        self.checkSubclasses()\n\n    def test_config_args(self):\n        TestConfigurable.configure(None, a=3)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 3)\n\n        obj = TestConfigurable(42, a=4)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 4)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig1()\n        self.assertIs(obj.a, None)\n\n    def test_config_class_args(self):\n        TestConfigurable.configure(TestConfig2, b=5)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 5)\n\n        obj = TestConfigurable(42, b=6)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 6)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig2()\n        self.assertIs(obj.b, None)\n\n    def test_config_multi_level(self):\n        TestConfigurable.configure(TestConfig3, a=1)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig3A)\n        self.assertEqual(obj.a, 1)\n\n        TestConfigurable.configure(TestConfig3)\n        TestConfig3.configure(TestConfig3B, b=2)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig3B)\n        self.assertEqual(obj.b, 2)\n\n    def test_config_inner_level(self):\n        # The inner level can be used even when the outer level\n        # doesn't point to it.\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3A)\n\n        TestConfig3.configure(TestConfig3B)\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3B)\n\n        # Configuring the base doesn't configure the inner.\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        TestConfigurable.configure(TestConfig2)\n\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3B)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 82,
                                "end_lineno": 188,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/util_test.py",
                            "type": "method",
                            "name": "ConfigurableTest.test_config_multi_level",
                            "content": "class ConfigurableTest(unittest.TestCase):\n    def setUp(self):\n        self.saved = TestConfigurable._save_configuration()\n        self.saved3 = TestConfig3._save_configuration()\n\n    def tearDown(self):\n        TestConfigurable._restore_configuration(self.saved)\n        TestConfig3._restore_configuration(self.saved3)\n\n    def checkSubclasses(self):\n        # no matter how the class is configured, it should always be\n        # possible to instantiate the subclasses directly\n        self.assertIsInstance(TestConfig1(), TestConfig1)\n        self.assertIsInstance(TestConfig2(), TestConfig2)\n\n        obj = TestConfig1(a=1)\n        self.assertEqual(obj.a, 1)\n        obj = TestConfig2(b=2)\n        self.assertEqual(obj.b, 2)\n\n    def test_default(self):\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertIs(obj.a, None)\n\n        obj = TestConfigurable(a=1)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 1)\n\n        self.checkSubclasses()\n\n    def test_config_class(self):\n        TestConfigurable.configure(TestConfig2)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertIs(obj.b, None)\n\n        obj = TestConfigurable(b=2)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 2)\n\n        self.checkSubclasses()\n\n    def test_config_args(self):\n        TestConfigurable.configure(None, a=3)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 3)\n\n        obj = TestConfigurable(42, a=4)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 4)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig1()\n        self.assertIs(obj.a, None)\n\n    def test_config_class_args(self):\n        TestConfigurable.configure(TestConfig2, b=5)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 5)\n\n        obj = TestConfigurable(42, b=6)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 6)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig2()\n        self.assertIs(obj.b, None)\n\n    def test_config_multi_level(self):\n        TestConfigurable.configure(TestConfig3, a=1)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig3A)\n        self.assertEqual(obj.a, 1)\n\n        TestConfigurable.configure(TestConfig3)\n        TestConfig3.configure(TestConfig3B, b=2)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig3B)\n        self.assertEqual(obj.b, 2)\n\n    def test_config_inner_level(self):\n        # The inner level can be used even when the outer level\n        # doesn't point to it.\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3A)\n\n        TestConfig3.configure(TestConfig3B)\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3B)\n\n        # Configuring the base doesn't configure the inner.\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        TestConfigurable.configure(TestConfig2)\n\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3B)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 157,
                            "end_lineno": 167,
                            "parent": {
                                "file_name": "tornado/test/util_test.py",
                                "type": "class",
                                "name": "ConfigurableTest",
                                "content": "class ConfigurableTest(unittest.TestCase):\n    def setUp(self):\n        self.saved = TestConfigurable._save_configuration()\n        self.saved3 = TestConfig3._save_configuration()\n\n    def tearDown(self):\n        TestConfigurable._restore_configuration(self.saved)\n        TestConfig3._restore_configuration(self.saved3)\n\n    def checkSubclasses(self):\n        # no matter how the class is configured, it should always be\n        # possible to instantiate the subclasses directly\n        self.assertIsInstance(TestConfig1(), TestConfig1)\n        self.assertIsInstance(TestConfig2(), TestConfig2)\n\n        obj = TestConfig1(a=1)\n        self.assertEqual(obj.a, 1)\n        obj = TestConfig2(b=2)\n        self.assertEqual(obj.b, 2)\n\n    def test_default(self):\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertIs(obj.a, None)\n\n        obj = TestConfigurable(a=1)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 1)\n\n        self.checkSubclasses()\n\n    def test_config_class(self):\n        TestConfigurable.configure(TestConfig2)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertIs(obj.b, None)\n\n        obj = TestConfigurable(b=2)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 2)\n\n        self.checkSubclasses()\n\n    def test_config_args(self):\n        TestConfigurable.configure(None, a=3)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 3)\n\n        obj = TestConfigurable(42, a=4)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 4)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig1()\n        self.assertIs(obj.a, None)\n\n    def test_config_class_args(self):\n        TestConfigurable.configure(TestConfig2, b=5)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 5)\n\n        obj = TestConfigurable(42, b=6)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 6)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig2()\n        self.assertIs(obj.b, None)\n\n    def test_config_multi_level(self):\n        TestConfigurable.configure(TestConfig3, a=1)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig3A)\n        self.assertEqual(obj.a, 1)\n\n        TestConfigurable.configure(TestConfig3)\n        TestConfig3.configure(TestConfig3B, b=2)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig3B)\n        self.assertEqual(obj.b, 2)\n\n    def test_config_inner_level(self):\n        # The inner level can be used even when the outer level\n        # doesn't point to it.\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3A)\n\n        TestConfig3.configure(TestConfig3B)\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3B)\n\n        # Configuring the base doesn't configure the inner.\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        TestConfigurable.configure(TestConfig2)\n\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3B)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 82,
                                "end_lineno": 188,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "\"\"\"Miscellaneous utility functions and classes.\n\nThis module is used internally by Tornado.  It is not necessarily expected\nthat the functions and classes defined here will be useful to other\napplications, but they are documented here in case they are.\n\nThe one public-facing part of this module is the `Configurable` class\nand its `~Configurable.configure` method, which becomes a part of the\ninterface of its subclasses, including `.AsyncHTTPClient`, `.IOLoop`,\nand `.Resolver`.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nimport array\nimport atexit\nimport os\nimport re\nimport sys\nimport zlib\n\nPY3 = sys.version_info >= (3,)\n\nif PY3:\n    xrange = range\n\n# inspect.getargspec() raises DeprecationWarnings in Python 3.5.\n# The two functions have compatible interfaces for the parts we need.\nif PY3:\n    from inspect import getfullargspec as getargspec\nelse:\n    from inspect import getargspec\n\n# Aliases for types that are spelled differently in different Python\n# versions. bytes_type is deprecated and no longer used in Tornado\n# itself but is left in case anyone outside Tornado is using it.\nbytes_type = bytes\nif PY3:\n    unicode_type = str\n    basestring_type = str\nelse:\n    # The names unicode and basestring don't exist in py3 so silence flake8.\n    unicode_type = unicode  # noqa\n    basestring_type = basestring  # noqa\n\n\ntry:\n    import typing  # noqa\n    from typing import cast\n\n    _ObjectDictBase = typing.Dict[str, typing.Any]\nexcept ImportError:\n    _ObjectDictBase = dict\n\n    def cast(typ, x):\n        return x\nelse:\n    # More imports that are only needed in type comments.\n    import datetime  # noqa\n    import types  # noqa\n    from typing import Any, AnyStr, Union, Optional, Dict, Mapping  # noqa\n    from typing import Tuple, Match, Callable  # noqa\n\n    if PY3:\n        _BaseString = str\n    else:\n        _BaseString = Union[bytes, unicode_type]\n\n\ntry:\n    from sys import is_finalizing\nexcept ImportError:\n    # Emulate it\n    def _get_emulated_is_finalizing():\n        L = []\n        atexit.register(lambda: L.append(None))\n\n        def is_finalizing():\n            # Not referencing any globals here\n            return L != []\n\n        return is_finalizing\n\n    is_finalizing = _get_emulated_is_finalizing()\n\n\nclass ObjectDict(_ObjectDictBase):\n    \"\"\"Makes a dictionary behave like an object, with attribute-style access.\n    \"\"\"\n    def __getattr__(self, name):\n        # type: (str) -> Any\n        try:\n            return self[name]\n        except KeyError:\n            raise AttributeError(name)\n\n    def __setattr__(self, name, value):\n        # type: (str, Any) -> None\n        self[name] = value\n\n\nclass GzipDecompressor(object):\n    \"\"\"Streaming gzip decompressor.\n\n    The interface is like that of `zlib.decompressobj` (without some of the\n    optional arguments, but it understands gzip headers and checksums.\n    \"\"\"\n    def __init__(self):\n        # Magic parameter makes zlib module understand gzip header\n        # http://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib\n        # This works on cpython and pypy, but not jython.\n        self.decompressobj = zlib.decompressobj(16 + zlib.MAX_WBITS)\n\n    def decompress(self, value, max_length=None):\n        # type: (bytes, Optional[int]) -> bytes\n        \"\"\"Decompress a chunk, returning newly-available data.\n\n        Some data may be buffered for later processing; `flush` must\n        be called when there is no more input data to ensure that\n        all data was processed.\n\n        If ``max_length`` is given, some input data may be left over\n        in ``unconsumed_tail``; you must retrieve this value and pass\n        it back to a future call to `decompress` if it is not empty.\n        \"\"\"\n        return self.decompressobj.decompress(value, max_length)\n\n    @property\n    def unconsumed_tail(self):\n        # type: () -> bytes\n        \"\"\"Returns the unconsumed portion left over\n        \"\"\"\n        return self.decompressobj.unconsumed_tail\n\n    def flush(self):\n        # type: () -> bytes\n        \"\"\"Return any remaining buffered data not yet returned by decompress.\n\n        Also checks for errors such as truncated input.\n        No other methods may be called on this object after `flush`.\n        \"\"\"\n        return self.decompressobj.flush()\n\n\ndef import_object(name):\n    # type: (_BaseString) -> Any\n    \"\"\"Imports an object by name.\n\n    import_object('x') is equivalent to 'import x'.\n    import_object('x.y.z') is equivalent to 'from x.y import z'.\n\n    >>> import tornado.escape\n    >>> import_object('tornado.escape') is tornado.escape\n    True\n    >>> import_object('tornado.escape.utf8') is tornado.escape.utf8\n    True\n    >>> import_object('tornado') is tornado\n    True\n    >>> import_object('tornado.missing_module')\n    Traceback (most recent call last):\n        ...\n    ImportError: No module named missing_module\n    \"\"\"\n    if not isinstance(name, str):\n        # on python 2 a byte string is required.\n        name = name.encode('utf-8')\n    if name.count('.') == 0:\n        return __import__(name, None, None)\n\n    parts = name.split('.')\n    obj = __import__('.'.join(parts[:-1]), None, None, [parts[-1]], 0)\n    try:\n        return getattr(obj, parts[-1])\n    except AttributeError:\n        raise ImportError(\"No module named %s\" % parts[-1])\n\n\n# Stubs to make mypy happy (and later for actual type-checking).\ndef raise_exc_info(exc_info):\n    # type: (Tuple[type, BaseException, types.TracebackType]) -> None\n    pass\n\n\ndef exec_in(code, glob, loc=None):\n    # type: (Any, Dict[str, Any], Optional[Mapping[str, Any]]) -> Any\n    if isinstance(code, basestring_type):\n        # exec(string) inherits the caller's future imports; compile\n        # the string first to prevent that.\n        code = compile(code, '<string>', 'exec', dont_inherit=True)\n    exec(code, glob, loc)\n\n\nif PY3:\n    exec(\"\"\"\ndef raise_exc_info(exc_info):\n    try:\n        raise exc_info[1].with_traceback(exc_info[2])\n    finally:\n        exc_info = None\n\n\"\"\")\nelse:\n    exec(\"\"\"\ndef raise_exc_info(exc_info):\n    raise exc_info[0], exc_info[1], exc_info[2]\n\"\"\")\n\n\ndef errno_from_exception(e):\n    # type: (BaseException) -> Optional[int]\n    \"\"\"Provides the errno from an Exception object.\n\n    There are cases that the errno attribute was not set so we pull\n    the errno out of the args but if someone instantiates an Exception\n    without any args you will get a tuple error. So this function\n    abstracts all that behavior to give you a safe way to get the\n    errno.\n    \"\"\"\n\n    if hasattr(e, 'errno'):\n        return e.errno  # type: ignore\n    elif e.args:\n        return e.args[0]\n    else:\n        return None\n\n\n_alphanum = frozenset(\n    \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\")\n\n\ndef _re_unescape_replacement(match):\n    # type: (Match[str]) -> str\n    group = match.group(1)\n    if group[0] in _alphanum:\n        raise ValueError(\"cannot unescape '\\\\\\\\%s'\" % group[0])\n    return group\n\n\n_re_unescape_pattern = re.compile(r'\\\\(.)', re.DOTALL)\n\n\ndef re_unescape(s):\n    # type: (str) -> str\n    \"\"\"Unescape a string escaped by `re.escape`.\n\n    May raise ``ValueError`` for regular expressions which could not\n    have been produced by `re.escape` (for example, strings containing\n    ``\\d`` cannot be unescaped).\n\n    .. versionadded:: 4.4\n    \"\"\"\n    return _re_unescape_pattern.sub(_re_unescape_replacement, s)\n\n\nclass Configurable(object):\n    \"\"\"Base class for configurable interfaces.\n\n    A configurable interface is an (abstract) class whose constructor\n    acts as a factory function for one of its implementation subclasses.\n    The implementation subclass as well as optional keyword arguments to\n    its initializer can be set globally at runtime with `configure`.\n\n    By using the constructor as the factory method, the interface\n    looks like a normal class, `isinstance` works as usual, etc.  This\n    pattern is most useful when the choice of implementation is likely\n    to be a global decision (e.g. when `~select.epoll` is available,\n    always use it instead of `~select.select`), or when a\n    previously-monolithic class has been split into specialized\n    subclasses.\n\n    Configurable subclasses must define the class methods\n    `configurable_base` and `configurable_default`, and use the instance\n    method `initialize` instead of ``__init__``.\n    \"\"\"\n    __impl_class = None  # type: type\n    __impl_kwargs = None  # type: Dict[str, Any]\n\n    def __new__(cls, *args, **kwargs):\n        base = cls.configurable_base()\n        init_kwargs = {}\n        if cls is base:\n            impl = cls.configured_class()\n            if base.__impl_kwargs:\n                init_kwargs.update(base.__impl_kwargs)\n        else:\n            impl = cls\n        init_kwargs.update(kwargs)\n        instance = super(Configurable, cls).__new__(impl)\n        # initialize vs __init__ chosen for compatibility with AsyncHTTPClient\n        # singleton magic.  If we get rid of that we can switch to __init__\n        # here too.\n        instance.initialize(*args, **init_kwargs)\n        return instance\n\n    @classmethod\n    def configurable_base(cls):\n        # type: () -> Any\n        # TODO: This class needs https://github.com/python/typing/issues/107\n        # to be fully typeable.\n        \"\"\"Returns the base class of a configurable hierarchy.\n\n        This will normally return the class in which it is defined.\n        (which is *not* necessarily the same as the cls classmethod parameter).\n        \"\"\"\n        raise NotImplementedError()\n\n    @classmethod\n    def configurable_default(cls):\n        # type: () -> type\n        \"\"\"Returns the implementation class to be used if none is configured.\"\"\"\n        raise NotImplementedError()\n\n    def initialize(self):\n        # type: () -> None\n        \"\"\"Initialize a `Configurable` subclass instance.\n\n        Configurable classes should use `initialize` instead of ``__init__``.\n\n        .. versionchanged:: 4.2\n           Now accepts positional arguments in addition to keyword arguments.\n        \"\"\"\n\n    @classmethod\n    def configure(cls, impl, **kwargs):\n        # type: (Any, **Any) -> None\n        \"\"\"Sets the class to use when the base class is instantiated.\n\n        Keyword arguments will be saved and added to the arguments passed\n        to the constructor.  This can be used to set global defaults for\n        some parameters.\n        \"\"\"\n        base = cls.configurable_base()\n        if isinstance(impl, (str, unicode_type)):\n            impl = import_object(impl)\n        if impl is not None and not issubclass(impl, cls):\n            raise ValueError(\"Invalid subclass of %s\" % cls)\n        base.__impl_class = impl\n        base.__impl_kwargs = kwargs\n\n    @classmethod\n    def configured_class(cls):\n        # type: () -> type\n        \"\"\"Returns the currently configured class.\"\"\"\n        base = cls.configurable_base()\n        if cls.__impl_class is None:\n            base.__impl_class = cls.configurable_default()\n        return base.__impl_class\n\n    @classmethod\n    def _save_configuration(cls):\n        # type: () -> Tuple[type, Dict[str, Any]]\n        base = cls.configurable_base()\n        return (base.__impl_class, base.__impl_kwargs)\n\n    @classmethod\n    def _restore_configuration(cls, saved):\n        # type: (Tuple[type, Dict[str, Any]]) -> None\n        base = cls.configurable_base()\n        base.__impl_class = saved[0]\n        base.__impl_kwargs = saved[1]\n\n\nclass ArgReplacer(object):\n    \"\"\"Replaces one value in an ``args, kwargs`` pair.\n\n    Inspects the function signature to find an argument by name\n    whether it is passed by position or keyword.  For use in decorators\n    and similar wrappers.\n    \"\"\"\n    def __init__(self, func, name):\n        # type: (Callable, str) -> None\n        self.name = name\n        try:\n            self.arg_pos = self._getargnames(func).index(name)\n        except ValueError:\n            # Not a positional parameter\n            self.arg_pos = None\n\n    def _getargnames(self, func):\n        # type: (Callable) -> List[str]\n        try:\n            return getargspec(func).args\n        except TypeError:\n            if hasattr(func, 'func_code'):\n                # Cython-generated code has all the attributes needed\n                # by inspect.getargspec, but the inspect module only\n                # works with ordinary functions. Inline the portion of\n                # getargspec that we need here. Note that for static\n                # functions the @cython.binding(True) decorator must\n                # be used (for methods it works out of the box).\n                code = func.func_code  # type: ignore\n                return code.co_varnames[:code.co_argcount]\n            raise\n\n    def get_old_value(self, args, kwargs, default=None):\n        # type: (List[Any], Dict[str, Any], Any) -> Any\n        \"\"\"Returns the old value of the named argument without replacing it.\n\n        Returns ``default`` if the argument is not present.\n        \"\"\"\n        if self.arg_pos is not None and len(args) > self.arg_pos:\n            return args[self.arg_pos]\n        else:\n            return kwargs.get(self.name, default)\n\n    def replace(self, new_value, args, kwargs):\n        # type: (Any, List[Any], Dict[str, Any]) -> Tuple[Any, List[Any], Dict[str, Any]]\n        \"\"\"Replace the named argument in ``args, kwargs`` with ``new_value``.\n\n        Returns ``(old_value, args, kwargs)``.  The returned ``args`` and\n        ``kwargs`` objects may not be the same as the input objects, or\n        the input objects may be mutated.\n\n        If the named argument was not found, ``new_value`` will be added\n        to ``kwargs`` and None will be returned as ``old_value``.\n        \"\"\"\n        if self.arg_pos is not None and len(args) > self.arg_pos:\n            # The arg to replace is passed positionally\n            old_value = args[self.arg_pos]\n            args = list(args)  # *args is normally a tuple\n            args[self.arg_pos] = new_value\n        else:\n            # The arg to replace is either omitted or passed by keyword.\n            old_value = kwargs.get(self.name)\n            kwargs[self.name] = new_value\n        return old_value, args, kwargs\n\n\ndef timedelta_to_seconds(td):\n    # type: (datetime.timedelta) -> float\n    \"\"\"Equivalent to td.total_seconds() (introduced in python 2.7).\"\"\"\n    return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / float(10 ** 6)\n\n\ndef _websocket_mask_python(mask, data):\n    # type: (bytes, bytes) -> bytes\n    \"\"\"Websocket masking function.\n\n    `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length.\n    Returns a `bytes` object of the same length as `data` with the mask applied\n    as specified in section 5.3 of RFC 6455.\n\n    This pure-python implementation may be replaced by an optimized version when available.\n    \"\"\"\n    mask_arr = array.array(\"B\", mask)\n    unmasked_arr = array.array(\"B\", data)\n    for i in xrange(len(data)):\n        unmasked_arr[i] = unmasked_arr[i] ^ mask_arr[i % 4]\n    if PY3:\n        # tostring was deprecated in py32.  It hasn't been removed,\n        # but since we turn on deprecation warnings in our tests\n        # we need to use the right one.\n        return unmasked_arr.tobytes()\n    else:\n        return unmasked_arr.tostring()\n\n\nif (os.environ.get('TORNADO_NO_EXTENSION') or\n        os.environ.get('TORNADO_EXTENSION') == '0'):\n    # These environment variables exist to make it easier to do performance\n    # comparisons; they are not guaranteed to remain supported in the future.\n    _websocket_mask = _websocket_mask_python\nelse:\n    try:\n        from tornado.speedups import websocket_mask as _websocket_mask\n    except ImportError:\n        if os.environ.get('TORNADO_EXTENSION') == '1':\n            raise\n        _websocket_mask = _websocket_mask_python\n\n\ndef doctests():\n    import doctest\n    return doctest.DocTestSuite()\n",
            "new_file_content": "\"\"\"Miscellaneous utility functions and classes.\n\nThis module is used internally by Tornado.  It is not necessarily expected\nthat the functions and classes defined here will be useful to other\napplications, but they are documented here in case they are.\n\nThe one public-facing part of this module is the `Configurable` class\nand its `~Configurable.configure` method, which becomes a part of the\ninterface of its subclasses, including `.AsyncHTTPClient`, `.IOLoop`,\nand `.Resolver`.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nimport array\nimport atexit\nimport os\nimport re\nimport sys\nimport zlib\n\nPY3 = sys.version_info >= (3,)\n\nif PY3:\n    xrange = range\n\n# inspect.getargspec() raises DeprecationWarnings in Python 3.5.\n# The two functions have compatible interfaces for the parts we need.\nif PY3:\n    from inspect import getfullargspec as getargspec\nelse:\n    from inspect import getargspec\n\n# Aliases for types that are spelled differently in different Python\n# versions. bytes_type is deprecated and no longer used in Tornado\n# itself but is left in case anyone outside Tornado is using it.\nbytes_type = bytes\nif PY3:\n    unicode_type = str\n    basestring_type = str\nelse:\n    # The names unicode and basestring don't exist in py3 so silence flake8.\n    unicode_type = unicode  # noqa\n    basestring_type = basestring  # noqa\n\n\ntry:\n    import typing  # noqa\n    from typing import cast\n\n    _ObjectDictBase = typing.Dict[str, typing.Any]\nexcept ImportError:\n    _ObjectDictBase = dict\n\n    def cast(typ, x):\n        return x\nelse:\n    # More imports that are only needed in type comments.\n    import datetime  # noqa\n    import types  # noqa\n    from typing import Any, AnyStr, Union, Optional, Dict, Mapping  # noqa\n    from typing import Tuple, Match, Callable  # noqa\n\n    if PY3:\n        _BaseString = str\n    else:\n        _BaseString = Union[bytes, unicode_type]\n\n\ntry:\n    from sys import is_finalizing\nexcept ImportError:\n    # Emulate it\n    def _get_emulated_is_finalizing():\n        L = []\n        atexit.register(lambda: L.append(None))\n\n        def is_finalizing():\n            # Not referencing any globals here\n            return L != []\n\n        return is_finalizing\n\n    is_finalizing = _get_emulated_is_finalizing()\n\n\nclass ObjectDict(_ObjectDictBase):\n    \"\"\"Makes a dictionary behave like an object, with attribute-style access.\n    \"\"\"\n    def __getattr__(self, name):\n        # type: (str) -> Any\n        try:\n            return self[name]\n        except KeyError:\n            raise AttributeError(name)\n\n    def __setattr__(self, name, value):\n        # type: (str, Any) -> None\n        self[name] = value\n\n\nclass GzipDecompressor(object):\n    \"\"\"Streaming gzip decompressor.\n\n    The interface is like that of `zlib.decompressobj` (without some of the\n    optional arguments, but it understands gzip headers and checksums.\n    \"\"\"\n    def __init__(self):\n        # Magic parameter makes zlib module understand gzip header\n        # http://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib\n        # This works on cpython and pypy, but not jython.\n        self.decompressobj = zlib.decompressobj(16 + zlib.MAX_WBITS)\n\n    def decompress(self, value, max_length=None):\n        # type: (bytes, Optional[int]) -> bytes\n        \"\"\"Decompress a chunk, returning newly-available data.\n\n        Some data may be buffered for later processing; `flush` must\n        be called when there is no more input data to ensure that\n        all data was processed.\n\n        If ``max_length`` is given, some input data may be left over\n        in ``unconsumed_tail``; you must retrieve this value and pass\n        it back to a future call to `decompress` if it is not empty.\n        \"\"\"\n        return self.decompressobj.decompress(value, max_length)\n\n    @property\n    def unconsumed_tail(self):\n        # type: () -> bytes\n        \"\"\"Returns the unconsumed portion left over\n        \"\"\"\n        return self.decompressobj.unconsumed_tail\n\n    def flush(self):\n        # type: () -> bytes\n        \"\"\"Return any remaining buffered data not yet returned by decompress.\n\n        Also checks for errors such as truncated input.\n        No other methods may be called on this object after `flush`.\n        \"\"\"\n        return self.decompressobj.flush()\n\n\ndef import_object(name):\n    # type: (_BaseString) -> Any\n    \"\"\"Imports an object by name.\n\n    import_object('x') is equivalent to 'import x'.\n    import_object('x.y.z') is equivalent to 'from x.y import z'.\n\n    >>> import tornado.escape\n    >>> import_object('tornado.escape') is tornado.escape\n    True\n    >>> import_object('tornado.escape.utf8') is tornado.escape.utf8\n    True\n    >>> import_object('tornado') is tornado\n    True\n    >>> import_object('tornado.missing_module')\n    Traceback (most recent call last):\n        ...\n    ImportError: No module named missing_module\n    \"\"\"\n    if not isinstance(name, str):\n        # on python 2 a byte string is required.\n        name = name.encode('utf-8')\n    if name.count('.') == 0:\n        return __import__(name, None, None)\n\n    parts = name.split('.')\n    obj = __import__('.'.join(parts[:-1]), None, None, [parts[-1]], 0)\n    try:\n        return getattr(obj, parts[-1])\n    except AttributeError:\n        raise ImportError(\"No module named %s\" % parts[-1])\n\n\n# Stubs to make mypy happy (and later for actual type-checking).\ndef raise_exc_info(exc_info):\n    # type: (Tuple[type, BaseException, types.TracebackType]) -> None\n    pass\n\n\ndef exec_in(code, glob, loc=None):\n    # type: (Any, Dict[str, Any], Optional[Mapping[str, Any]]) -> Any\n    if isinstance(code, basestring_type):\n        # exec(string) inherits the caller's future imports; compile\n        # the string first to prevent that.\n        code = compile(code, '<string>', 'exec', dont_inherit=True)\n    exec(code, glob, loc)\n\n\nif PY3:\n    exec(\"\"\"\ndef raise_exc_info(exc_info):\n    try:\n        raise exc_info[1].with_traceback(exc_info[2])\n    finally:\n        exc_info = None\n\n\"\"\")\nelse:\n    exec(\"\"\"\ndef raise_exc_info(exc_info):\n    raise exc_info[0], exc_info[1], exc_info[2]\n\"\"\")\n\n\ndef errno_from_exception(e):\n    # type: (BaseException) -> Optional[int]\n    \"\"\"Provides the errno from an Exception object.\n\n    There are cases that the errno attribute was not set so we pull\n    the errno out of the args but if someone instantiates an Exception\n    without any args you will get a tuple error. So this function\n    abstracts all that behavior to give you a safe way to get the\n    errno.\n    \"\"\"\n\n    if hasattr(e, 'errno'):\n        return e.errno  # type: ignore\n    elif e.args:\n        return e.args[0]\n    else:\n        return None\n\n\n_alphanum = frozenset(\n    \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\")\n\n\ndef _re_unescape_replacement(match):\n    # type: (Match[str]) -> str\n    group = match.group(1)\n    if group[0] in _alphanum:\n        raise ValueError(\"cannot unescape '\\\\\\\\%s'\" % group[0])\n    return group\n\n\n_re_unescape_pattern = re.compile(r'\\\\(.)', re.DOTALL)\n\n\ndef re_unescape(s):\n    # type: (str) -> str\n    \"\"\"Unescape a string escaped by `re.escape`.\n\n    May raise ``ValueError`` for regular expressions which could not\n    have been produced by `re.escape` (for example, strings containing\n    ``\\d`` cannot be unescaped).\n\n    .. versionadded:: 4.4\n    \"\"\"\n    return _re_unescape_pattern.sub(_re_unescape_replacement, s)\n\n\nclass Configurable(object):\n    \"\"\"Base class for configurable interfaces.\n\n    A configurable interface is an (abstract) class whose constructor\n    acts as a factory function for one of its implementation subclasses.\n    The implementation subclass as well as optional keyword arguments to\n    its initializer can be set globally at runtime with `configure`.\n\n    By using the constructor as the factory method, the interface\n    looks like a normal class, `isinstance` works as usual, etc.  This\n    pattern is most useful when the choice of implementation is likely\n    to be a global decision (e.g. when `~select.epoll` is available,\n    always use it instead of `~select.select`), or when a\n    previously-monolithic class has been split into specialized\n    subclasses.\n\n    Configurable subclasses must define the class methods\n    `configurable_base` and `configurable_default`, and use the instance\n    method `initialize` instead of ``__init__``.\n    \"\"\"\n    __impl_class = None  # type: type\n    __impl_kwargs = None  # type: Dict[str, Any]\n\n    def __new__(cls, *args, **kwargs):\n        base = cls.configurable_base()\n        init_kwargs = {}\n        if cls is base:\n            impl = cls.configured_class()\n            if base.__impl_kwargs:\n                init_kwargs.update(base.__impl_kwargs)\n        else:\n            impl = cls\n        init_kwargs.update(kwargs)\n        if impl.configurable_base() is not base:\n            # The impl class is itself configurable, so recurse.\n            return impl(*args, **init_kwargs)\n        instance = super(Configurable, cls).__new__(impl)\n        # initialize vs __init__ chosen for compatibility with AsyncHTTPClient\n        # singleton magic.  If we get rid of that we can switch to __init__\n        # here too.\n        instance.initialize(*args, **init_kwargs)\n        return instance\n\n    @classmethod\n    def configurable_base(cls):\n        # type: () -> Any\n        # TODO: This class needs https://github.com/python/typing/issues/107\n        # to be fully typeable.\n        \"\"\"Returns the base class of a configurable hierarchy.\n\n        This will normally return the class in which it is defined.\n        (which is *not* necessarily the same as the cls classmethod parameter).\n        \"\"\"\n        raise NotImplementedError()\n\n    @classmethod\n    def configurable_default(cls):\n        # type: () -> type\n        \"\"\"Returns the implementation class to be used if none is configured.\"\"\"\n        raise NotImplementedError()\n\n    def initialize(self):\n        # type: () -> None\n        \"\"\"Initialize a `Configurable` subclass instance.\n\n        Configurable classes should use `initialize` instead of ``__init__``.\n\n        .. versionchanged:: 4.2\n           Now accepts positional arguments in addition to keyword arguments.\n        \"\"\"\n\n    @classmethod\n    def configure(cls, impl, **kwargs):\n        # type: (Any, **Any) -> None\n        \"\"\"Sets the class to use when the base class is instantiated.\n\n        Keyword arguments will be saved and added to the arguments passed\n        to the constructor.  This can be used to set global defaults for\n        some parameters.\n        \"\"\"\n        base = cls.configurable_base()\n        if isinstance(impl, (str, unicode_type)):\n            impl = import_object(impl)\n        if impl is not None and not issubclass(impl, cls):\n            raise ValueError(\"Invalid subclass of %s\" % cls)\n        base.__impl_class = impl\n        base.__impl_kwargs = kwargs\n\n    @classmethod\n    def configured_class(cls):\n        # type: () -> type\n        \"\"\"Returns the currently configured class.\"\"\"\n        base = cls.configurable_base()\n        # Manually mangle the private name to see whether this base\n        # has been configured (and not another base higher in the\n        # hierarchy).\n        if base.__dict__.get('_Configurable__impl_class') is None:\n            base.__impl_class = cls.configurable_default()\n        return base.__impl_class\n\n    @classmethod\n    def _save_configuration(cls):\n        # type: () -> Tuple[type, Dict[str, Any]]\n        base = cls.configurable_base()\n        return (base.__impl_class, base.__impl_kwargs)\n\n    @classmethod\n    def _restore_configuration(cls, saved):\n        # type: (Tuple[type, Dict[str, Any]]) -> None\n        base = cls.configurable_base()\n        base.__impl_class = saved[0]\n        base.__impl_kwargs = saved[1]\n\n\nclass ArgReplacer(object):\n    \"\"\"Replaces one value in an ``args, kwargs`` pair.\n\n    Inspects the function signature to find an argument by name\n    whether it is passed by position or keyword.  For use in decorators\n    and similar wrappers.\n    \"\"\"\n    def __init__(self, func, name):\n        # type: (Callable, str) -> None\n        self.name = name\n        try:\n            self.arg_pos = self._getargnames(func).index(name)\n        except ValueError:\n            # Not a positional parameter\n            self.arg_pos = None\n\n    def _getargnames(self, func):\n        # type: (Callable) -> List[str]\n        try:\n            return getargspec(func).args\n        except TypeError:\n            if hasattr(func, 'func_code'):\n                # Cython-generated code has all the attributes needed\n                # by inspect.getargspec, but the inspect module only\n                # works with ordinary functions. Inline the portion of\n                # getargspec that we need here. Note that for static\n                # functions the @cython.binding(True) decorator must\n                # be used (for methods it works out of the box).\n                code = func.func_code  # type: ignore\n                return code.co_varnames[:code.co_argcount]\n            raise\n\n    def get_old_value(self, args, kwargs, default=None):\n        # type: (List[Any], Dict[str, Any], Any) -> Any\n        \"\"\"Returns the old value of the named argument without replacing it.\n\n        Returns ``default`` if the argument is not present.\n        \"\"\"\n        if self.arg_pos is not None and len(args) > self.arg_pos:\n            return args[self.arg_pos]\n        else:\n            return kwargs.get(self.name, default)\n\n    def replace(self, new_value, args, kwargs):\n        # type: (Any, List[Any], Dict[str, Any]) -> Tuple[Any, List[Any], Dict[str, Any]]\n        \"\"\"Replace the named argument in ``args, kwargs`` with ``new_value``.\n\n        Returns ``(old_value, args, kwargs)``.  The returned ``args`` and\n        ``kwargs`` objects may not be the same as the input objects, or\n        the input objects may be mutated.\n\n        If the named argument was not found, ``new_value`` will be added\n        to ``kwargs`` and None will be returned as ``old_value``.\n        \"\"\"\n        if self.arg_pos is not None and len(args) > self.arg_pos:\n            # The arg to replace is passed positionally\n            old_value = args[self.arg_pos]\n            args = list(args)  # *args is normally a tuple\n            args[self.arg_pos] = new_value\n        else:\n            # The arg to replace is either omitted or passed by keyword.\n            old_value = kwargs.get(self.name)\n            kwargs[self.name] = new_value\n        return old_value, args, kwargs\n\n\ndef timedelta_to_seconds(td):\n    # type: (datetime.timedelta) -> float\n    \"\"\"Equivalent to td.total_seconds() (introduced in python 2.7).\"\"\"\n    return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / float(10 ** 6)\n\n\ndef _websocket_mask_python(mask, data):\n    # type: (bytes, bytes) -> bytes\n    \"\"\"Websocket masking function.\n\n    `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length.\n    Returns a `bytes` object of the same length as `data` with the mask applied\n    as specified in section 5.3 of RFC 6455.\n\n    This pure-python implementation may be replaced by an optimized version when available.\n    \"\"\"\n    mask_arr = array.array(\"B\", mask)\n    unmasked_arr = array.array(\"B\", data)\n    for i in xrange(len(data)):\n        unmasked_arr[i] = unmasked_arr[i] ^ mask_arr[i % 4]\n    if PY3:\n        # tostring was deprecated in py32.  It hasn't been removed,\n        # but since we turn on deprecation warnings in our tests\n        # we need to use the right one.\n        return unmasked_arr.tobytes()\n    else:\n        return unmasked_arr.tostring()\n\n\nif (os.environ.get('TORNADO_NO_EXTENSION') or\n        os.environ.get('TORNADO_EXTENSION') == '0'):\n    # These environment variables exist to make it easier to do performance\n    # comparisons; they are not guaranteed to remain supported in the future.\n    _websocket_mask = _websocket_mask_python\nelse:\n    try:\n        from tornado.speedups import websocket_mask as _websocket_mask\n    except ImportError:\n        if os.environ.get('TORNADO_EXTENSION') == '1':\n            raise\n        _websocket_mask = _websocket_mask_python\n\n\ndef doctests():\n    import doctest\n    return doctest.DocTestSuite()\n",
            "header": {
                "file": {
                    "path": "tornado/util.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "981b94c8",
                "new_commit_hash": "bfd80beb",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/util.py"
            },
            "plus_file": {
                "path": "b/tornado/util.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 286,
                            "length": 6
                        },
                        "new_range": {
                            "start": 286,
                            "length": 9
                        },
                        "section": "class Configurable(object):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        else:",
                                "type": "context"
                            },
                            {
                                "content": "            impl = cls",
                                "type": "context"
                            },
                            {
                                "content": "        init_kwargs.update(kwargs)",
                                "type": "context"
                            },
                            {
                                "content": "        if impl.configurable_base() is not base:",
                                "type": "added"
                            },
                            {
                                "content": "            # The impl class is itself configurable, so recurse.",
                                "type": "added"
                            },
                            {
                                "content": "            return impl(*args, **init_kwargs)",
                                "type": "added"
                            },
                            {
                                "content": "        instance = super(Configurable, cls).__new__(impl)",
                                "type": "context"
                            },
                            {
                                "content": "        # initialize vs __init__ chosen for compatibility with AsyncHTTPClient",
                                "type": "context"
                            },
                            {
                                "content": "        # singleton magic.  If we get rid of that we can switch to __init__",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/util.py",
                            "type": "method",
                            "name": "Configurable.__new__",
                            "content": "class Configurable(object):\n    \"\"\"Base class for configurable interfaces.\n\n    A configurable interface is an (abstract) class whose constructor\n    acts as a factory function for one of its implementation subclasses.\n    The implementation subclass as well as optional keyword arguments to\n    its initializer can be set globally at runtime with `configure`.\n\n    By using the constructor as the factory method, the interface\n    looks like a normal class, `isinstance` works as usual, etc.  This\n    pattern is most useful when the choice of implementation is likely\n    to be a global decision (e.g. when `~select.epoll` is available,\n    always use it instead of `~select.select`), or when a\n    previously-monolithic class has been split into specialized\n    subclasses.\n\n    Configurable subclasses must define the class methods\n    `configurable_base` and `configurable_default`, and use the instance\n    method `initialize` instead of ``__init__``.\n    \"\"\"\n    __impl_class = None  # type: type\n    __impl_kwargs = None  # type: Dict[str, Any]\n\n    def __new__(cls, *args, **kwargs):\n        base = cls.configurable_base()\n        init_kwargs = {}\n        if cls is base:\n            impl = cls.configured_class()\n            if base.__impl_kwargs:\n                init_kwargs.update(base.__impl_kwargs)\n        else:\n            impl = cls\n        init_kwargs.update(kwargs)\n        if impl.configurable_base() is not base:\n            # The impl class is itself configurable, so recurse.\n            return impl(*args, **init_kwargs)\n        instance = super(Configurable, cls).__new__(impl)\n        # initialize vs __init__ chosen for compatibility with AsyncHTTPClient\n        # singleton magic.  If we get rid of that we can switch to __init__\n        # here too.\n        instance.initialize(*args, **init_kwargs)\n        return instance\n\n    @classmethod\n    def configurable_base(cls):\n        # type: () -> Any\n        # TODO: This class needs https://github.com/python/typing/issues/107\n        # to be fully typeable.\n        \"\"\"Returns the base class of a configurable hierarchy.\n\n        This will normally return the class in which it is defined.\n        (which is *not* necessarily the same as the cls classmethod parameter).\n        \"\"\"\n        raise NotImplementedError()\n\n    @classmethod\n    def configurable_default(cls):\n        # type: () -> type\n        \"\"\"Returns the implementation class to be used if none is configured.\"\"\"\n        raise NotImplementedError()\n\n    def initialize(self):\n        # type: () -> None\n        \"\"\"Initialize a `Configurable` subclass instance.\n\n        Configurable classes should use `initialize` instead of ``__init__``.\n\n        .. versionchanged:: 4.2\n           Now accepts positional arguments in addition to keyword arguments.\n        \"\"\"\n\n    @classmethod\n    def configure(cls, impl, **kwargs):\n        # type: (Any, **Any) -> None\n        \"\"\"Sets the class to use when the base class is instantiated.\n\n        Keyword arguments will be saved and added to the arguments passed\n        to the constructor.  This can be used to set global defaults for\n        some parameters.\n        \"\"\"\n        base = cls.configurable_base()\n        if isinstance(impl, (str, unicode_type)):\n            impl = import_object(impl)\n        if impl is not None and not issubclass(impl, cls):\n            raise ValueError(\"Invalid subclass of %s\" % cls)\n        base.__impl_class = impl\n        base.__impl_kwargs = kwargs\n\n    @classmethod\n    def configured_class(cls):\n        # type: () -> type\n        \"\"\"Returns the currently configured class.\"\"\"\n        base = cls.configurable_base()\n        # Manually mangle the private name to see whether this base\n        # has been configured (and not another base higher in the\n        # hierarchy).\n        if base.__dict__.get('_Configurable__impl_class') is None:\n            base.__impl_class = cls.configurable_default()\n        return base.__impl_class\n\n    @classmethod\n    def _save_configuration(cls):\n        # type: () -> Tuple[type, Dict[str, Any]]\n        base = cls.configurable_base()\n        return (base.__impl_class, base.__impl_kwargs)\n\n    @classmethod\n    def _restore_configuration(cls, saved):\n        # type: (Tuple[type, Dict[str, Any]]) -> None\n        base = cls.configurable_base()\n        base.__impl_class = saved[0]\n        base.__impl_kwargs = saved[1]",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 279,
                            "end_lineno": 297,
                            "parent": {
                                "file_name": "tornado/util.py",
                                "type": "class",
                                "name": "Configurable",
                                "content": "class Configurable(object):\n    \"\"\"Base class for configurable interfaces.\n\n    A configurable interface is an (abstract) class whose constructor\n    acts as a factory function for one of its implementation subclasses.\n    The implementation subclass as well as optional keyword arguments to\n    its initializer can be set globally at runtime with `configure`.\n\n    By using the constructor as the factory method, the interface\n    looks like a normal class, `isinstance` works as usual, etc.  This\n    pattern is most useful when the choice of implementation is likely\n    to be a global decision (e.g. when `~select.epoll` is available,\n    always use it instead of `~select.select`), or when a\n    previously-monolithic class has been split into specialized\n    subclasses.\n\n    Configurable subclasses must define the class methods\n    `configurable_base` and `configurable_default`, and use the instance\n    method `initialize` instead of ``__init__``.\n    \"\"\"\n    __impl_class = None  # type: type\n    __impl_kwargs = None  # type: Dict[str, Any]\n\n    def __new__(cls, *args, **kwargs):\n        base = cls.configurable_base()\n        init_kwargs = {}\n        if cls is base:\n            impl = cls.configured_class()\n            if base.__impl_kwargs:\n                init_kwargs.update(base.__impl_kwargs)\n        else:\n            impl = cls\n        init_kwargs.update(kwargs)\n        if impl.configurable_base() is not base:\n            # The impl class is itself configurable, so recurse.\n            return impl(*args, **init_kwargs)\n        instance = super(Configurable, cls).__new__(impl)\n        # initialize vs __init__ chosen for compatibility with AsyncHTTPClient\n        # singleton magic.  If we get rid of that we can switch to __init__\n        # here too.\n        instance.initialize(*args, **init_kwargs)\n        return instance\n\n    @classmethod\n    def configurable_base(cls):\n        # type: () -> Any\n        # TODO: This class needs https://github.com/python/typing/issues/107\n        # to be fully typeable.\n        \"\"\"Returns the base class of a configurable hierarchy.\n\n        This will normally return the class in which it is defined.\n        (which is *not* necessarily the same as the cls classmethod parameter).\n        \"\"\"\n        raise NotImplementedError()\n\n    @classmethod\n    def configurable_default(cls):\n        # type: () -> type\n        \"\"\"Returns the implementation class to be used if none is configured.\"\"\"\n        raise NotImplementedError()\n\n    def initialize(self):\n        # type: () -> None\n        \"\"\"Initialize a `Configurable` subclass instance.\n\n        Configurable classes should use `initialize` instead of ``__init__``.\n\n        .. versionchanged:: 4.2\n           Now accepts positional arguments in addition to keyword arguments.\n        \"\"\"\n\n    @classmethod\n    def configure(cls, impl, **kwargs):\n        # type: (Any, **Any) -> None\n        \"\"\"Sets the class to use when the base class is instantiated.\n\n        Keyword arguments will be saved and added to the arguments passed\n        to the constructor.  This can be used to set global defaults for\n        some parameters.\n        \"\"\"\n        base = cls.configurable_base()\n        if isinstance(impl, (str, unicode_type)):\n            impl = import_object(impl)\n        if impl is not None and not issubclass(impl, cls):\n            raise ValueError(\"Invalid subclass of %s\" % cls)\n        base.__impl_class = impl\n        base.__impl_kwargs = kwargs\n\n    @classmethod\n    def configured_class(cls):\n        # type: () -> type\n        \"\"\"Returns the currently configured class.\"\"\"\n        base = cls.configurable_base()\n        # Manually mangle the private name to see whether this base\n        # has been configured (and not another base higher in the\n        # hierarchy).\n        if base.__dict__.get('_Configurable__impl_class') is None:\n            base.__impl_class = cls.configurable_default()\n        return base.__impl_class\n\n    @classmethod\n    def _save_configuration(cls):\n        # type: () -> Tuple[type, Dict[str, Any]]\n        base = cls.configurable_base()\n        return (base.__impl_class, base.__impl_kwargs)\n\n    @classmethod\n    def _restore_configuration(cls, saved):\n        # type: (Tuple[type, Dict[str, Any]]) -> None\n        base = cls.configurable_base()\n        base.__impl_class = saved[0]\n        base.__impl_kwargs = saved[1]",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 256,
                                "end_lineno": 367,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/util.py",
                            "type": "class",
                            "name": "Configurable",
                            "content": "class Configurable(object):\n    \"\"\"Base class for configurable interfaces.\n\n    A configurable interface is an (abstract) class whose constructor\n    acts as a factory function for one of its implementation subclasses.\n    The implementation subclass as well as optional keyword arguments to\n    its initializer can be set globally at runtime with `configure`.\n\n    By using the constructor as the factory method, the interface\n    looks like a normal class, `isinstance` works as usual, etc.  This\n    pattern is most useful when the choice of implementation is likely\n    to be a global decision (e.g. when `~select.epoll` is available,\n    always use it instead of `~select.select`), or when a\n    previously-monolithic class has been split into specialized\n    subclasses.\n\n    Configurable subclasses must define the class methods\n    `configurable_base` and `configurable_default`, and use the instance\n    method `initialize` instead of ``__init__``.\n    \"\"\"\n    __impl_class = None  # type: type\n    __impl_kwargs = None  # type: Dict[str, Any]\n\n    def __new__(cls, *args, **kwargs):\n        base = cls.configurable_base()\n        init_kwargs = {}\n        if cls is base:\n            impl = cls.configured_class()\n            if base.__impl_kwargs:\n                init_kwargs.update(base.__impl_kwargs)\n        else:\n            impl = cls\n        init_kwargs.update(kwargs)\n        if impl.configurable_base() is not base:\n            # The impl class is itself configurable, so recurse.\n            return impl(*args, **init_kwargs)\n        instance = super(Configurable, cls).__new__(impl)\n        # initialize vs __init__ chosen for compatibility with AsyncHTTPClient\n        # singleton magic.  If we get rid of that we can switch to __init__\n        # here too.\n        instance.initialize(*args, **init_kwargs)\n        return instance\n\n    @classmethod\n    def configurable_base(cls):\n        # type: () -> Any\n        # TODO: This class needs https://github.com/python/typing/issues/107\n        # to be fully typeable.\n        \"\"\"Returns the base class of a configurable hierarchy.\n\n        This will normally return the class in which it is defined.\n        (which is *not* necessarily the same as the cls classmethod parameter).\n        \"\"\"\n        raise NotImplementedError()\n\n    @classmethod\n    def configurable_default(cls):\n        # type: () -> type\n        \"\"\"Returns the implementation class to be used if none is configured.\"\"\"\n        raise NotImplementedError()\n\n    def initialize(self):\n        # type: () -> None\n        \"\"\"Initialize a `Configurable` subclass instance.\n\n        Configurable classes should use `initialize` instead of ``__init__``.\n\n        .. versionchanged:: 4.2\n           Now accepts positional arguments in addition to keyword arguments.\n        \"\"\"\n\n    @classmethod\n    def configure(cls, impl, **kwargs):\n        # type: (Any, **Any) -> None\n        \"\"\"Sets the class to use when the base class is instantiated.\n\n        Keyword arguments will be saved and added to the arguments passed\n        to the constructor.  This can be used to set global defaults for\n        some parameters.\n        \"\"\"\n        base = cls.configurable_base()\n        if isinstance(impl, (str, unicode_type)):\n            impl = import_object(impl)\n        if impl is not None and not issubclass(impl, cls):\n            raise ValueError(\"Invalid subclass of %s\" % cls)\n        base.__impl_class = impl\n        base.__impl_kwargs = kwargs\n\n    @classmethod\n    def configured_class(cls):\n        # type: () -> type\n        \"\"\"Returns the currently configured class.\"\"\"\n        base = cls.configurable_base()\n        # Manually mangle the private name to see whether this base\n        # has been configured (and not another base higher in the\n        # hierarchy).\n        if base.__dict__.get('_Configurable__impl_class') is None:\n            base.__impl_class = cls.configurable_default()\n        return base.__impl_class\n\n    @classmethod\n    def _save_configuration(cls):\n        # type: () -> Tuple[type, Dict[str, Any]]\n        base = cls.configurable_base()\n        return (base.__impl_class, base.__impl_kwargs)\n\n    @classmethod\n    def _restore_configuration(cls, saved):\n        # type: (Tuple[type, Dict[str, Any]]) -> None\n        base = cls.configurable_base()\n        base.__impl_class = saved[0]\n        base.__impl_kwargs = saved[1]",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 256,
                            "end_lineno": 367,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 343,
                            "length": 7
                        },
                        "new_range": {
                            "start": 346,
                            "length": 10
                        },
                        "section": "class Configurable(object):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        # type: () -> type",
                                "type": "context"
                            },
                            {
                                "content": "        \"\"\"Returns the currently configured class.\"\"\"",
                                "type": "context"
                            },
                            {
                                "content": "        base = cls.configurable_base()",
                                "type": "context"
                            },
                            {
                                "content": "        if cls.__impl_class is None:",
                                "type": "deleted"
                            },
                            {
                                "content": "        # Manually mangle the private name to see whether this base",
                                "type": "added"
                            },
                            {
                                "content": "        # has been configured (and not another base higher in the",
                                "type": "added"
                            },
                            {
                                "content": "        # hierarchy).",
                                "type": "added"
                            },
                            {
                                "content": "        if base.__dict__.get('_Configurable__impl_class') is None:",
                                "type": "added"
                            },
                            {
                                "content": "            base.__impl_class = cls.configurable_default()",
                                "type": "context"
                            },
                            {
                                "content": "        return base.__impl_class",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/util.py",
                            "type": "method",
                            "name": "Configurable.configured_class",
                            "content": "class Configurable(object):\n    \"\"\"Base class for configurable interfaces.\n\n    A configurable interface is an (abstract) class whose constructor\n    acts as a factory function for one of its implementation subclasses.\n    The implementation subclass as well as optional keyword arguments to\n    its initializer can be set globally at runtime with `configure`.\n\n    By using the constructor as the factory method, the interface\n    looks like a normal class, `isinstance` works as usual, etc.  This\n    pattern is most useful when the choice of implementation is likely\n    to be a global decision (e.g. when `~select.epoll` is available,\n    always use it instead of `~select.select`), or when a\n    previously-monolithic class has been split into specialized\n    subclasses.\n\n    Configurable subclasses must define the class methods\n    `configurable_base` and `configurable_default`, and use the instance\n    method `initialize` instead of ``__init__``.\n    \"\"\"\n    __impl_class = None  # type: type\n    __impl_kwargs = None  # type: Dict[str, Any]\n\n    def __new__(cls, *args, **kwargs):\n        base = cls.configurable_base()\n        init_kwargs = {}\n        if cls is base:\n            impl = cls.configured_class()\n            if base.__impl_kwargs:\n                init_kwargs.update(base.__impl_kwargs)\n        else:\n            impl = cls\n        init_kwargs.update(kwargs)\n        instance = super(Configurable, cls).__new__(impl)\n        # initialize vs __init__ chosen for compatibility with AsyncHTTPClient\n        # singleton magic.  If we get rid of that we can switch to __init__\n        # here too.\n        instance.initialize(*args, **init_kwargs)\n        return instance\n\n    @classmethod\n    def configurable_base(cls):\n        # type: () -> Any\n        # TODO: This class needs https://github.com/python/typing/issues/107\n        # to be fully typeable.\n        \"\"\"Returns the base class of a configurable hierarchy.\n\n        This will normally return the class in which it is defined.\n        (which is *not* necessarily the same as the cls classmethod parameter).\n        \"\"\"\n        raise NotImplementedError()\n\n    @classmethod\n    def configurable_default(cls):\n        # type: () -> type\n        \"\"\"Returns the implementation class to be used if none is configured.\"\"\"\n        raise NotImplementedError()\n\n    def initialize(self):\n        # type: () -> None\n        \"\"\"Initialize a `Configurable` subclass instance.\n\n        Configurable classes should use `initialize` instead of ``__init__``.\n\n        .. versionchanged:: 4.2\n           Now accepts positional arguments in addition to keyword arguments.\n        \"\"\"\n\n    @classmethod\n    def configure(cls, impl, **kwargs):\n        # type: (Any, **Any) -> None\n        \"\"\"Sets the class to use when the base class is instantiated.\n\n        Keyword arguments will be saved and added to the arguments passed\n        to the constructor.  This can be used to set global defaults for\n        some parameters.\n        \"\"\"\n        base = cls.configurable_base()\n        if isinstance(impl, (str, unicode_type)):\n            impl = import_object(impl)\n        if impl is not None and not issubclass(impl, cls):\n            raise ValueError(\"Invalid subclass of %s\" % cls)\n        base.__impl_class = impl\n        base.__impl_kwargs = kwargs\n\n    @classmethod\n    def configured_class(cls):\n        # type: () -> type\n        \"\"\"Returns the currently configured class.\"\"\"\n        base = cls.configurable_base()\n        if cls.__impl_class is None:\n            base.__impl_class = cls.configurable_default()\n        return base.__impl_class\n\n    @classmethod\n    def _save_configuration(cls):\n        # type: () -> Tuple[type, Dict[str, Any]]\n        base = cls.configurable_base()\n        return (base.__impl_class, base.__impl_kwargs)\n\n    @classmethod\n    def _restore_configuration(cls, saved):\n        # type: (Tuple[type, Dict[str, Any]]) -> None\n        base = cls.configurable_base()\n        base.__impl_class = saved[0]\n        base.__impl_kwargs = saved[1]",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 342,
                            "end_lineno": 348,
                            "parent": {
                                "file_name": "tornado/util.py",
                                "type": "class",
                                "name": "Configurable",
                                "content": "class Configurable(object):\n    \"\"\"Base class for configurable interfaces.\n\n    A configurable interface is an (abstract) class whose constructor\n    acts as a factory function for one of its implementation subclasses.\n    The implementation subclass as well as optional keyword arguments to\n    its initializer can be set globally at runtime with `configure`.\n\n    By using the constructor as the factory method, the interface\n    looks like a normal class, `isinstance` works as usual, etc.  This\n    pattern is most useful when the choice of implementation is likely\n    to be a global decision (e.g. when `~select.epoll` is available,\n    always use it instead of `~select.select`), or when a\n    previously-monolithic class has been split into specialized\n    subclasses.\n\n    Configurable subclasses must define the class methods\n    `configurable_base` and `configurable_default`, and use the instance\n    method `initialize` instead of ``__init__``.\n    \"\"\"\n    __impl_class = None  # type: type\n    __impl_kwargs = None  # type: Dict[str, Any]\n\n    def __new__(cls, *args, **kwargs):\n        base = cls.configurable_base()\n        init_kwargs = {}\n        if cls is base:\n            impl = cls.configured_class()\n            if base.__impl_kwargs:\n                init_kwargs.update(base.__impl_kwargs)\n        else:\n            impl = cls\n        init_kwargs.update(kwargs)\n        instance = super(Configurable, cls).__new__(impl)\n        # initialize vs __init__ chosen for compatibility with AsyncHTTPClient\n        # singleton magic.  If we get rid of that we can switch to __init__\n        # here too.\n        instance.initialize(*args, **init_kwargs)\n        return instance\n\n    @classmethod\n    def configurable_base(cls):\n        # type: () -> Any\n        # TODO: This class needs https://github.com/python/typing/issues/107\n        # to be fully typeable.\n        \"\"\"Returns the base class of a configurable hierarchy.\n\n        This will normally return the class in which it is defined.\n        (which is *not* necessarily the same as the cls classmethod parameter).\n        \"\"\"\n        raise NotImplementedError()\n\n    @classmethod\n    def configurable_default(cls):\n        # type: () -> type\n        \"\"\"Returns the implementation class to be used if none is configured.\"\"\"\n        raise NotImplementedError()\n\n    def initialize(self):\n        # type: () -> None\n        \"\"\"Initialize a `Configurable` subclass instance.\n\n        Configurable classes should use `initialize` instead of ``__init__``.\n\n        .. versionchanged:: 4.2\n           Now accepts positional arguments in addition to keyword arguments.\n        \"\"\"\n\n    @classmethod\n    def configure(cls, impl, **kwargs):\n        # type: (Any, **Any) -> None\n        \"\"\"Sets the class to use when the base class is instantiated.\n\n        Keyword arguments will be saved and added to the arguments passed\n        to the constructor.  This can be used to set global defaults for\n        some parameters.\n        \"\"\"\n        base = cls.configurable_base()\n        if isinstance(impl, (str, unicode_type)):\n            impl = import_object(impl)\n        if impl is not None and not issubclass(impl, cls):\n            raise ValueError(\"Invalid subclass of %s\" % cls)\n        base.__impl_class = impl\n        base.__impl_kwargs = kwargs\n\n    @classmethod\n    def configured_class(cls):\n        # type: () -> type\n        \"\"\"Returns the currently configured class.\"\"\"\n        base = cls.configurable_base()\n        if cls.__impl_class is None:\n            base.__impl_class = cls.configurable_default()\n        return base.__impl_class\n\n    @classmethod\n    def _save_configuration(cls):\n        # type: () -> Tuple[type, Dict[str, Any]]\n        base = cls.configurable_base()\n        return (base.__impl_class, base.__impl_kwargs)\n\n    @classmethod\n    def _restore_configuration(cls, saved):\n        # type: (Tuple[type, Dict[str, Any]]) -> None\n        base = cls.configurable_base()\n        base.__impl_class = saved[0]\n        base.__impl_kwargs = saved[1]",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 256,
                                "end_lineno": 361,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/util.py",
                            "type": "class",
                            "name": "Configurable",
                            "content": "class Configurable(object):\n    \"\"\"Base class for configurable interfaces.\n\n    A configurable interface is an (abstract) class whose constructor\n    acts as a factory function for one of its implementation subclasses.\n    The implementation subclass as well as optional keyword arguments to\n    its initializer can be set globally at runtime with `configure`.\n\n    By using the constructor as the factory method, the interface\n    looks like a normal class, `isinstance` works as usual, etc.  This\n    pattern is most useful when the choice of implementation is likely\n    to be a global decision (e.g. when `~select.epoll` is available,\n    always use it instead of `~select.select`), or when a\n    previously-monolithic class has been split into specialized\n    subclasses.\n\n    Configurable subclasses must define the class methods\n    `configurable_base` and `configurable_default`, and use the instance\n    method `initialize` instead of ``__init__``.\n    \"\"\"\n    __impl_class = None  # type: type\n    __impl_kwargs = None  # type: Dict[str, Any]\n\n    def __new__(cls, *args, **kwargs):\n        base = cls.configurable_base()\n        init_kwargs = {}\n        if cls is base:\n            impl = cls.configured_class()\n            if base.__impl_kwargs:\n                init_kwargs.update(base.__impl_kwargs)\n        else:\n            impl = cls\n        init_kwargs.update(kwargs)\n        instance = super(Configurable, cls).__new__(impl)\n        # initialize vs __init__ chosen for compatibility with AsyncHTTPClient\n        # singleton magic.  If we get rid of that we can switch to __init__\n        # here too.\n        instance.initialize(*args, **init_kwargs)\n        return instance\n\n    @classmethod\n    def configurable_base(cls):\n        # type: () -> Any\n        # TODO: This class needs https://github.com/python/typing/issues/107\n        # to be fully typeable.\n        \"\"\"Returns the base class of a configurable hierarchy.\n\n        This will normally return the class in which it is defined.\n        (which is *not* necessarily the same as the cls classmethod parameter).\n        \"\"\"\n        raise NotImplementedError()\n\n    @classmethod\n    def configurable_default(cls):\n        # type: () -> type\n        \"\"\"Returns the implementation class to be used if none is configured.\"\"\"\n        raise NotImplementedError()\n\n    def initialize(self):\n        # type: () -> None\n        \"\"\"Initialize a `Configurable` subclass instance.\n\n        Configurable classes should use `initialize` instead of ``__init__``.\n\n        .. versionchanged:: 4.2\n           Now accepts positional arguments in addition to keyword arguments.\n        \"\"\"\n\n    @classmethod\n    def configure(cls, impl, **kwargs):\n        # type: (Any, **Any) -> None\n        \"\"\"Sets the class to use when the base class is instantiated.\n\n        Keyword arguments will be saved and added to the arguments passed\n        to the constructor.  This can be used to set global defaults for\n        some parameters.\n        \"\"\"\n        base = cls.configurable_base()\n        if isinstance(impl, (str, unicode_type)):\n            impl = import_object(impl)\n        if impl is not None and not issubclass(impl, cls):\n            raise ValueError(\"Invalid subclass of %s\" % cls)\n        base.__impl_class = impl\n        base.__impl_kwargs = kwargs\n\n    @classmethod\n    def configured_class(cls):\n        # type: () -> type\n        \"\"\"Returns the currently configured class.\"\"\"\n        base = cls.configurable_base()\n        if cls.__impl_class is None:\n            base.__impl_class = cls.configurable_default()\n        return base.__impl_class\n\n    @classmethod\n    def _save_configuration(cls):\n        # type: () -> Tuple[type, Dict[str, Any]]\n        base = cls.configurable_base()\n        return (base.__impl_class, base.__impl_kwargs)\n\n    @classmethod\n    def _restore_configuration(cls, saved):\n        # type: (Tuple[type, Dict[str, Any]]) -> None\n        base = cls.configurable_base()\n        base.__impl_class = saved[0]\n        base.__impl_kwargs = saved[1]",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 256,
                            "end_lineno": 361,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "6453ce8f2e553d5a1f393975daa89bc5a21e70f6^",
    "new_commit_hash": "6453ce8f2e553d5a1f393975daa89bc5a21e70f6",
    "commit_message": "util: Enable multiple configurable bases in one hierarchy\n\nThis allows a mid-level class like PollIOLoop to have its own\nconfigurability.",
    "commit_date": "2017-05-27T19:10:45-04:00",
    "metadata": {}
}
{
    "repo_name": "tornado",
    "new_commit_hash": "6453ce8f2e553d5a1f393975daa89bc5a21e70f6",
    "test_file_codes": [
        "# coding: utf-8\nfrom __future__ import absolute_import, division, print_function\nimport re\nimport sys\nimport datetime\n\nimport tornado.escape\nfrom tornado.escape import utf8\nfrom tornado.util import raise_exc_info, Configurable, exec_in, ArgReplacer, timedelta_to_seconds, import_object, re_unescape, is_finalizing, PY3\nfrom tornado.test.util import unittest\n\nif PY3:\n    from io import StringIO\nelse:\n    from cStringIO import StringIO\n\n\nclass RaiseExcInfoTest(unittest.TestCase):\n    def test_two_arg_exception(self):\n        # This test would fail on python 3 if raise_exc_info were simply\n        # a three-argument raise statement, because TwoArgException\n        # doesn't have a \"copy constructor\"\n        class TwoArgException(Exception):\n            def __init__(self, a, b):\n                super(TwoArgException, self).__init__()\n                self.a, self.b = a, b\n\n        try:\n            raise TwoArgException(1, 2)\n        except TwoArgException:\n            exc_info = sys.exc_info()\n        try:\n            raise_exc_info(exc_info)\n            self.fail(\"didn't get expected exception\")\n        except TwoArgException as e:\n            self.assertIs(e, exc_info[1])\n\n\nclass TestConfigurable(Configurable):\n    @classmethod\n    def configurable_base(cls):\n        return TestConfigurable\n\n    @classmethod\n    def configurable_default(cls):\n        return TestConfig1\n\n\nclass TestConfig1(TestConfigurable):\n    def initialize(self, pos_arg=None, a=None):\n        self.a = a\n        self.pos_arg = pos_arg\n\n\nclass TestConfig2(TestConfigurable):\n    def initialize(self, pos_arg=None, b=None):\n        self.b = b\n        self.pos_arg = pos_arg\n\n\nclass TestConfig3(TestConfigurable):\n    # TestConfig3 is a configuration option that is itself configurable.\n    @classmethod\n    def configurable_base(cls):\n        return TestConfig3\n\n    @classmethod\n    def configurable_default(cls):\n        return TestConfig3A\n\n\nclass TestConfig3A(TestConfig3):\n    def initialize(self, a=None):\n        self.a = a\n\n\nclass TestConfig3B(TestConfig3):\n    def initialize(self, b=None):\n        self.b = b\n\n\nclass ConfigurableTest(unittest.TestCase):\n    def setUp(self):\n        self.saved = TestConfigurable._save_configuration()\n        self.saved3 = TestConfig3._save_configuration()\n\n    def tearDown(self):\n        TestConfigurable._restore_configuration(self.saved)\n        TestConfig3._restore_configuration(self.saved3)\n\n    def checkSubclasses(self):\n        # no matter how the class is configured, it should always be\n        # possible to instantiate the subclasses directly\n        self.assertIsInstance(TestConfig1(), TestConfig1)\n        self.assertIsInstance(TestConfig2(), TestConfig2)\n\n        obj = TestConfig1(a=1)\n        self.assertEqual(obj.a, 1)\n        obj = TestConfig2(b=2)\n        self.assertEqual(obj.b, 2)\n\n    def test_default(self):\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertIs(obj.a, None)\n\n        obj = TestConfigurable(a=1)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 1)\n\n        self.checkSubclasses()\n\n    def test_config_class(self):\n        TestConfigurable.configure(TestConfig2)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertIs(obj.b, None)\n\n        obj = TestConfigurable(b=2)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 2)\n\n        self.checkSubclasses()\n\n    def test_config_args(self):\n        TestConfigurable.configure(None, a=3)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 3)\n\n        obj = TestConfigurable(42, a=4)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 4)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig1()\n        self.assertIs(obj.a, None)\n\n    def test_config_class_args(self):\n        TestConfigurable.configure(TestConfig2, b=5)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 5)\n\n        obj = TestConfigurable(42, b=6)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 6)\n        self.assertEqual(obj.pos_arg, 42)\n\n        self.checkSubclasses()\n        # args bound in configure don't apply when using the subclass directly\n        obj = TestConfig2()\n        self.assertIs(obj.b, None)\n\n    def test_config_multi_level(self):\n        TestConfigurable.configure(TestConfig3, a=1)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig3A)\n        self.assertEqual(obj.a, 1)\n\n        TestConfigurable.configure(TestConfig3)\n        TestConfig3.configure(TestConfig3B, b=2)\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig3B)\n        self.assertEqual(obj.b, 2)\n\n    def test_config_inner_level(self):\n        # The inner level can be used even when the outer level\n        # doesn't point to it.\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3A)\n\n        TestConfig3.configure(TestConfig3B)\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3B)\n\n        # Configuring the base doesn't configure the inner.\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig1)\n        TestConfigurable.configure(TestConfig2)\n\n        obj = TestConfigurable()\n        self.assertIsInstance(obj, TestConfig2)\n\n        obj = TestConfig3()\n        self.assertIsInstance(obj, TestConfig3B)\n\n\nclass UnicodeLiteralTest(unittest.TestCase):\n    def test_unicode_escapes(self):\n        self.assertEqual(utf8(u'\\u00e9'), b'\\xc3\\xa9')\n\n\nclass ExecInTest(unittest.TestCase):\n    # This test is python 2 only because there are no new future imports\n    # defined in python 3 yet.\n    @unittest.skipIf(sys.version_info >= print_function.getMandatoryRelease(),\n                     'no testable future imports')\n    def test_no_inherit_future(self):\n        # This file has from __future__ import print_function...\n        f = StringIO()\n        print('hello', file=f)\n        # ...but the template doesn't\n        exec_in('print >> f, \"world\"', dict(f=f))\n        self.assertEqual(f.getvalue(), 'hello\\nworld\\n')\n\n\nclass ArgReplacerTest(unittest.TestCase):\n    def setUp(self):\n        def function(x, y, callback=None, z=None):\n            pass\n        self.replacer = ArgReplacer(function, 'callback')\n\n    def test_omitted(self):\n        args = (1, 2)\n        kwargs = dict()\n        self.assertIs(self.replacer.get_old_value(args, kwargs), None)\n        self.assertEqual(self.replacer.replace('new', args, kwargs),\n                         (None, (1, 2), dict(callback='new')))\n\n    def test_position(self):\n        args = (1, 2, 'old', 3)\n        kwargs = dict()\n        self.assertEqual(self.replacer.get_old_value(args, kwargs), 'old')\n        self.assertEqual(self.replacer.replace('new', args, kwargs),\n                         ('old', [1, 2, 'new', 3], dict()))\n\n    def test_keyword(self):\n        args = (1,)\n        kwargs = dict(y=2, callback='old', z=3)\n        self.assertEqual(self.replacer.get_old_value(args, kwargs), 'old')\n        self.assertEqual(self.replacer.replace('new', args, kwargs),\n                         ('old', (1,), dict(y=2, callback='new', z=3)))\n\n\nclass TimedeltaToSecondsTest(unittest.TestCase):\n    def test_timedelta_to_seconds(self):\n        time_delta = datetime.timedelta(hours=1)\n        self.assertEqual(timedelta_to_seconds(time_delta), 3600.0)\n\n\nclass ImportObjectTest(unittest.TestCase):\n    def test_import_member(self):\n        self.assertIs(import_object('tornado.escape.utf8'), utf8)\n\n    def test_import_member_unicode(self):\n        self.assertIs(import_object(u'tornado.escape.utf8'), utf8)\n\n    def test_import_module(self):\n        self.assertIs(import_object('tornado.escape'), tornado.escape)\n\n    def test_import_module_unicode(self):\n        # The internal implementation of __import__ differs depending on\n        # whether the thing being imported is a module or not.\n        # This variant requires a byte string in python 2.\n        self.assertIs(import_object(u'tornado.escape'), tornado.escape)\n\n\nclass ReUnescapeTest(unittest.TestCase):\n    def test_re_unescape(self):\n        test_strings = (\n            '/favicon.ico',\n            'index.html',\n            'Hello, World!',\n            '!$@#%;',\n        )\n        for string in test_strings:\n            self.assertEqual(string, re_unescape(re.escape(string)))\n\n    def test_re_unescape_raises_error_on_invalid_input(self):\n        with self.assertRaises(ValueError):\n            re_unescape('\\\\d')\n        with self.assertRaises(ValueError):\n            re_unescape('\\\\b')\n        with self.assertRaises(ValueError):\n            re_unescape('\\\\Z')\n\n\nclass IsFinalizingTest(unittest.TestCase):\n    def test_basic(self):\n        self.assertFalse(is_finalizing())\n",
        "#!/usr/bin/env python\nimport unittest\nimport sys\nimport time\nimport traceback\nimport platform\nimport os\n\n\nclass PytestLikeResult(unittest.TestResult):\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.start_time = None\n        # Store (test, outcome, info) for each test:\n        #   outcome ∈ { \"passed\", \"failed\", \"error\", \"skipped\" }\n        #   info can hold the exception or skip reason, etc.\n        self.results = []\n\n    def startTestRun(self):\n        \"\"\"Called once before all tests.\"\"\"\n        self.start_time = time.time()\n        # Print a header similar to pytest\n        print(\"=\" * 29 + \" test session starts \" + \"=\" * 29)\n        # You can customize the platform/versions/paths as you like:\n        print(\n            f\"platform {platform.system().lower()} -- Python {platform.python_version()}\"\n        )\n        print(f\"rootdir: {os.path.abspath(os.curdir)}\")\n\n    def stopTestRun(self):\n        \"\"\"Called once after all tests are done.\"\"\"\n        elapsed = time.time() - self.start_time\n        print()  # blank line after final dot\n\n        # Summarize\n        ntests = len(self.results)\n        print(f\"collected {ntests} items\")\n\n        # Show details of failures/errors\n        failures = [r for r in self.results if r[1] == \"failed\"]\n        errors = [r for r in self.results if r[1] == \"error\"]\n\n        if failures:\n            print(\"\\n\" + \"=\" * 35 + \" FAILURES \" + \"=\" * 35)\n            for test, outcome, err_info in failures:\n                test = test.split(\"::\")\n                if len(test) == 3:\n                    test = f\"{test[1]}.{test[2]}\"\n                else:\n                    test = f\"{test[1]}\"\n                print(f\"__________ {test} __________\")\n                self._print_traceback(err_info)\n        if errors:\n            print(\"\\n\" + \"=\" * 35 + \" ERRORS \" + \"=\" * 37)\n            for test, outcome, err_info in errors:\n                test = test.split(\"::\")\n                if len(test) == 3:\n                    test = f\"{test[1]}.{test[2]}\"\n                else:\n                    test = f\"{test[1]}\"\n                print(f\"__________ {test} __________\")\n                self._print_traceback(err_info)\n\n        # Optional short summary lines for passes/fails/skips\n        print(\"\\n==================== short test summary info ====================\")\n        for test, outcome, info in self.results:\n            if outcome in (\"passed\", \"failed\", \"error\", \"skipped\"):\n                print(f\"{outcome.upper()} {test}\")\n\n        # Final one-line summary: “1 failed, 1 errors, 10 passed in 2.04s”\n        passed_count = sum(1 for r in self.results if r[1] == \"passed\")\n        failed_count = len(failures)\n        error_count = len(errors)\n        skipped_count = sum(1 for r in self.results if r[1] == \"skipped\")\n\n        summary_bits = []\n        if failed_count:\n            summary_bits.append(f\"{failed_count} failed\")\n        if error_count:\n            summary_bits.append(f\"{error_count} error{'s' if error_count != 1 else ''}\")\n        if passed_count:\n            summary_bits.append(f\"{passed_count} passed\")\n        if skipped_count:\n            summary_bits.append(f\"{skipped_count} skipped\")\n\n        summary_str = \", \".join(summary_bits) if summary_bits else \"no tests run\"\n        print(\n            f\"=================== {summary_str} in {elapsed:.2f}s ===================\"\n        )\n\n    def startTest(self, test):\n        \"\"\"Called right before each test method.\"\"\"\n        super().startTest(test)\n        # Print a dot or some indicator\n        print(\".\", end=\"\", flush=True)\n\n    def addSuccess(self, test):\n        super().addSuccess(test)\n        self.results.append((self._test_id(test), \"passed\", None))\n\n    def addFailure(self, test, err):\n        super().addFailure(test, err)\n        self.results.append((self._test_id(test), \"failed\", err))\n\n    def addError(self, test, err):\n        super().addError(test, err)\n        self.results.append((self._test_id(test), \"error\", err))\n\n    def addSkip(self, test, reason):\n        super().addSkip(test, reason)\n        self.results.append((self._test_id(test), \"skipped\", reason))\n\n    def _print_traceback(self, err_info):\n        \"\"\"Helper to print the traceback like pytest does.\"\"\"\n        if isinstance(err_info, tuple) and len(err_info) == 3:\n            exc_type, exc_value, tb = err_info\n            traceback.print_exception(exc_type, exc_value, tb, file=sys.stdout)\n        else:\n            print(str(err_info))\n\n    def _test_id(self, test):\n        try:\n            return f\"{test.__class__.__module__}::{test.__class__.__name__}::{test._testMethodName}\"\n        except AttributeError:\n            # Fallback for _ErrorHolder objects\n            return f\"{test.__class__.__module__}::{test.__class__.__name__}\"\n\n\nclass PytestLikeRunner(unittest.TextTestRunner):\n    \"\"\"A custom TextTestRunner that uses the PytestLikeResult.\"\"\"\n\n    resultclass = PytestLikeResult\n\n    def run(self, test):\n        result = self._makeResult()\n        # Overriding run to ensure we call startTestRun/stopTestRun\n        result.startTestRun()\n        test(result)\n        result.stopTestRun()\n        return result\n\n    def tearDown(self):\n        # Reset signal handlers\n        from twisted.internet import reactor\n\n        reactor.removeAll()\n        reactor.stop()\n        super().tearDown()\n\n\ndef main():\n    loader = unittest.TestLoader()\n    suite = loader.discover(\".\", pattern=\"test_*.py\")  # discover tests in r2e_tests/\n    runner = PytestLikeRunner(verbosity=0)\n    result = runner.run(suite)\n    # Exit with code 0 if all tests passed/skipped, 1 if there were fails/errors\n    sys.exit(not result.wasSuccessful())\n\n\nif __name__ == \"__main__\":\n    main()\n"
    ],
    "test_file_names": [
        "test_1.py",
        "tornado_unittest_runner.py"
    ],
    "setup_res_code": 0,
    "setup_res_stdout": "",
    "setup_res_stderr": "Using CPython 3.9.21\nCreating virtual environment at: .venv\nActivate with: source .venv/bin/activate\nResolved 1 package in 807ms\nPrepared 1 package in 1.17s\nInstalled 1 package in 0.95ms\n + tornado==5.0.dev1 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_6453ce8f2e553d5a1f393975daa89bc5a21e70f6)\nResolved 29 packages in 13ms\nInstalled 29 packages in 80ms\n + attrs==24.3.0\n + automat==24.8.1\n + cachetools==5.5.0\n + cffi==1.17.1\n + chardet==5.2.0\n + colorama==0.4.6\n + constantly==23.10.4\n + distlib==0.3.9\n + exceptiongroup==1.2.2\n + filelock==3.16.1\n + hyperlink==21.0.0\n + idna==3.10\n + incremental==24.7.2\n + iniconfig==2.0.0\n + packaging==24.2\n + platformdirs==4.3.6\n + pluggy==1.5.0\n + pycares==4.5.0\n + pycparser==2.22\n + pycurl==7.45.4\n + pyproject-api==1.8.0\n + pytest==8.3.4\n + setuptools==75.6.0\n + tomli==2.2.1\n + tox==4.23.2\n + twisted==24.11.0\n + typing-extensions==4.12.2\n + virtualenv==20.28.0\n + zope-interface==7.2\n",
    "new_commit_res_code": 0,
    "new_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_6453ce8f2e553d5a1f393975daa89bc5a21e70f6\n....................\ncollected 20 items\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::ArgReplacerTest::test_keyword\nPASSED r2e_tests.test_1::ArgReplacerTest::test_omitted\nPASSED r2e_tests.test_1::ArgReplacerTest::test_position\nPASSED r2e_tests.test_1::ConfigurableTest::test_config_args\nPASSED r2e_tests.test_1::ConfigurableTest::test_config_class\nPASSED r2e_tests.test_1::ConfigurableTest::test_config_class_args\nPASSED r2e_tests.test_1::ConfigurableTest::test_config_inner_level\nPASSED r2e_tests.test_1::ConfigurableTest::test_config_multi_level\nPASSED r2e_tests.test_1::ConfigurableTest::test_default\nSKIPPED r2e_tests.test_1::ExecInTest::test_no_inherit_future\nPASSED r2e_tests.test_1::ImportObjectTest::test_import_member\nPASSED r2e_tests.test_1::ImportObjectTest::test_import_member_unicode\nPASSED r2e_tests.test_1::ImportObjectTest::test_import_module\nPASSED r2e_tests.test_1::ImportObjectTest::test_import_module_unicode\nPASSED r2e_tests.test_1::IsFinalizingTest::test_basic\nPASSED r2e_tests.test_1::RaiseExcInfoTest::test_two_arg_exception\nPASSED r2e_tests.test_1::ReUnescapeTest::test_re_unescape\nPASSED r2e_tests.test_1::ReUnescapeTest::test_re_unescape_raises_error_on_invalid_input\nPASSED r2e_tests.test_1::TimedeltaToSecondsTest::test_timedelta_to_seconds\nPASSED r2e_tests.test_1::UnicodeLiteralTest::test_unicode_escapes\n=================== 19 passed, 1 skipped in 0.00s ===================\n",
    "new_commit_res_stderr": "",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_6453ce8f2e553d5a1f393975daa89bc5a21e70f6\n....................\ncollected 20 items\n\n=================================== ERRORS =====================================\n__________ ConfigurableTest.test_config_multi_level __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_6453ce8f2e553d5a1f393975daa89bc5a21e70f6/r2e_tests/test_1.py\", line 159, in test_config_multi_level\n    obj = TestConfigurable()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_6453ce8f2e553d5a1f393975daa89bc5a21e70f6/tornado/util.py\", line 293, in __new__\n    instance.initialize(*args, **init_kwargs)\nTypeError: initialize() got an unexpected keyword argument 'a'\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::ArgReplacerTest::test_keyword\nPASSED r2e_tests.test_1::ArgReplacerTest::test_omitted\nPASSED r2e_tests.test_1::ArgReplacerTest::test_position\nPASSED r2e_tests.test_1::ConfigurableTest::test_config_args\nPASSED r2e_tests.test_1::ConfigurableTest::test_config_class\nPASSED r2e_tests.test_1::ConfigurableTest::test_config_class_args\nPASSED r2e_tests.test_1::ConfigurableTest::test_config_inner_level\nERROR r2e_tests.test_1::ConfigurableTest::test_config_multi_level\nPASSED r2e_tests.test_1::ConfigurableTest::test_default\nSKIPPED r2e_tests.test_1::ExecInTest::test_no_inherit_future\nPASSED r2e_tests.test_1::ImportObjectTest::test_import_member\nPASSED r2e_tests.test_1::ImportObjectTest::test_import_member_unicode\nPASSED r2e_tests.test_1::ImportObjectTest::test_import_module\nPASSED r2e_tests.test_1::ImportObjectTest::test_import_module_unicode\nPASSED r2e_tests.test_1::IsFinalizingTest::test_basic\nPASSED r2e_tests.test_1::RaiseExcInfoTest::test_two_arg_exception\nPASSED r2e_tests.test_1::ReUnescapeTest::test_re_unescape\nPASSED r2e_tests.test_1::ReUnescapeTest::test_re_unescape_raises_error_on_invalid_input\nPASSED r2e_tests.test_1::TimedeltaToSecondsTest::test_timedelta_to_seconds\nPASSED r2e_tests.test_1::UnicodeLiteralTest::test_unicode_escapes\n=================== 1 error, 18 passed, 1 skipped in 0.00s ===================\n",
    "old_commit_res_stderr": ""
}
tornado/test/util_test.py tornado/util.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** Initialization Fails with Unexpected Keyword Argument When Using Multiple Configurable Bases

**Description:**
When configuring classes with multiple configurable bases, initializing an instance with specific keyword arguments results in a `TypeError`. This occurs because the initialization process does not correctly handle passing arguments through the hierarchy of configurable bases.

**Example:**
Consider the following configuration setup:

```python
class TestConfig3(TestConfigurable):
    @classmethod
    def configurable_base(cls):
        return TestConfig3

    @classmethod
    def configurable_default(cls):
        return TestConfig3A

class TestConfig3A(TestConfig3):
    def initialize(self, a=None):
        self.a = a

class TestConfig3B(TestConfig3):
    def initialize(self, b=None):
        self.b = b

# Configuration attempt
TestConfigurable.configure(TestConfig3, a=1)
obj = TestConfigurable()
```

**Expected Behavior:**
Initializing `TestConfigurable` with `a=1` should create an instance of `TestConfig3A` with the attribute `a` set to `1`.

**Actual Behavior:**
A `TypeError` is raised:
```
TypeError: initialize() got an unexpected keyword argument 'a'
```
This error indicates that the `initialize` method does not accept the keyword argument `a` when multiple configurable bases are involved.

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### tornado/util.py
"""Miscellaneous utility functions and classes.

This module is used internally by Tornado.  It is not necessarily expected
that the functions and classes defined here will be useful to other
applications, but they are documented here in case they are.

The one public-facing part of this module is the `Configurable` class
and its `~Configurable.configure` method, which becomes a part of the
interface of its subclasses, including `.AsyncHTTPClient`, `.IOLoop`,
and `.Resolver`.
"""

from __future__ import absolute_import, division, print_function

import array
import atexit
import os
import re
import sys
import zlib

PY3 = sys.version_info >= (3,)

if PY3:
    xrange = range

# inspect.getargspec() raises DeprecationWarnings in Python 3.5.
# The two functions have compatible interfaces for the parts we need.
if PY3:
    from inspect import getfullargspec as getargspec
else:
    from inspect import getargspec

# Aliases for types that are spelled differently in different Python
# versions. bytes_type is deprecated and no longer used in Tornado
# itself but is left in case anyone outside Tornado is using it.
bytes_type = bytes
if PY3:
    unicode_type = str
    basestring_type = str
else:
    # The names unicode and basestring don't exist in py3 so silence flake8.
    unicode_type = unicode  # noqa
    basestring_type = basestring  # noqa


try:
    import typing  # noqa
    from typing import cast

    _ObjectDictBase = typing.Dict[str, typing.Any]
except ImportError:
    _ObjectDictBase = dict

    def cast(typ, x):
        return x
else:
    # More imports that are only needed in type comments.
    import datetime  # noqa
    import types  # noqa
    from typing import Any, AnyStr, Union, Optional, Dict, Mapping  # noqa
    from typing import Tuple, Match, Callable  # noqa

    if PY3:
        _BaseString = str
    else:
        _BaseString = Union[bytes, unicode_type]


try:
    from sys import is_finalizing
except ImportError:
    # Emulate it
    def _get_emulated_is_finalizing():
        L = []
        atexit.register(lambda: L.append(None))

        def is_finalizing():
            # Not referencing any globals here
            return L != []

        return is_finalizing

    is_finalizing = _get_emulated_is_finalizing()


class ObjectDict(_ObjectDictBase):
    """Makes a dictionary behave like an object, with attribute-style access.
    """
    def __getattr__(self, name):
        # type: (str) -> Any
        try:
            return self[name]
        except KeyError:
            raise AttributeError(name)

    def __setattr__(self, name, value):
        # type: (str, Any) -> None
        self[name] = value


class GzipDecompressor(object):
    """Streaming gzip decompressor.

    The interface is like that of `zlib.decompressobj` (without some of the
    optional arguments, but it understands gzip headers and checksums.
    """
    def __init__(self):
        # Magic parameter makes zlib module understand gzip header
        # http://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib
        # This works on cpython and pypy, but not jython.
        self.decompressobj = zlib.decompressobj(16 + zlib.MAX_WBITS)

    def decompress(self, value, max_length=None):
        # type: (bytes, Optional[int]) -> bytes
        """Decompress a chunk, returning newly-available data.

        Some data may be buffered for later processing; `flush` must
        be called when there is no more input data to ensure that
        all data was processed.

        If ``max_length`` is given, some input data may be left over
        in ``unconsumed_tail``; you must retrieve this value and pass
        it back to a future call to `decompress` if it is not empty.
        """
        return self.decompressobj.decompress(value, max_length)

    @property
    def unconsumed_tail(self):
        # type: () -> bytes
        """Returns the unconsumed portion left over
        """
        return self.decompressobj.unconsumed_tail

    def flush(self):
        # type: () -> bytes
        """Return any remaining buffered data not yet returned by decompress.

        Also checks for errors such as truncated input.
        No other methods may be called on this object after `flush`.
        """
        return self.decompressobj.flush()


def import_object(name):
    # type: (_BaseString) -> Any
    """Imports an object by name.

    import_object('x') is equivalent to 'import x'.
    import_object('x.y.z') is equivalent to 'from x.y import z'.

    >>> import tornado.escape
    >>> import_object('tornado.escape') is tornado.escape
    True
    >>> import_object('tornado.escape.utf8') is tornado.escape.utf8
    True
    >>> import_object('tornado') is tornado
    True
    >>> import_object('tornado.missing_module')
    Traceback (most recent call last):
        ...
    ImportError: No module named missing_module
    """
    if not isinstance(name, str):
        # on python 2 a byte string is required.
        name = name.encode('utf-8')
    if name.count('.') == 0:
        return __import__(name, None, None)

    parts = name.split('.')
    obj = __import__('.'.join(parts[:-1]), None, None, [parts[-1]], 0)
    try:
        return getattr(obj, parts[-1])
    except AttributeError:
        raise ImportError("No module named %s" % parts[-1])


# Stubs to make mypy happy (and later for actual type-checking).
def raise_exc_info(exc_info):
    # type: (Tuple[type, BaseException, types.TracebackType]) -> None
    pass


def exec_in(code, glob, loc=None):
    # type: (Any, Dict[str, Any], Optional[Mapping[str, Any]]) -> Any
    if isinstance(code, basestring_type):
        # exec(string) inherits the caller's future imports; compile
        # the string first to prevent that.
        code = compile(code, '<string>', 'exec', dont_inherit=True)
    exec(code, glob, loc)


if PY3:
    exec("""
def raise_exc_info(exc_info):
    try:
        raise exc_info[1].with_traceback(exc_info[2])
    finally:
        exc_info = None

""")
else:
    exec("""
def raise_exc_info(exc_info):
    raise exc_info[0], exc_info[1], exc_info[2]
""")


def errno_from_exception(e):
    # type: (BaseException) -> Optional[int]
    """Provides the errno from an Exception object.

    There are cases that the errno attribute was not set so we pull
    the errno out of the args but if someone instantiates an Exception
    without any args you will get a tuple error. So this function
    abstracts all that behavior to give you a safe way to get the
    errno.
    """

    if hasattr(e, 'errno'):
        return e.errno  # type: ignore
    elif e.args:
        return e.args[0]
    else:
        return None


_alphanum = frozenset(
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")


def _re_unescape_replacement(match):
    # type: (Match[str]) -> str
    group = match.group(1)
    if group[0] in _alphanum:
        raise ValueError("cannot unescape '\\\\%s'" % group[0])
    return group


_re_unescape_pattern = re.compile(r'\\(.)', re.DOTALL)


def re_unescape(s):
    # type: (str) -> str
    """Unescape a string escaped by `re.escape`.

    May raise ``ValueError`` for regular expressions which could not
    have been produced by `re.escape` (for example, strings containing
    ``\d`` cannot be unescaped).

    .. versionadded:: 4.4
    """
    return _re_unescape_pattern.sub(_re_unescape_replacement, s)


class Configurable(object):
    """Base class for configurable interfaces.

    A configurable interface is an (abstract) class whose constructor
    acts as a factory function for one of its implementation subclasses.
    The implementation subclass as well as optional keyword arguments to
    its initializer can be set globally at runtime with `configure`.

    By using the constructor as the factory method, the interface
    looks like a normal class, `isinstance` works as usual, etc.  This
    pattern is most useful when the choice of implementation is likely
    to be a global decision (e.g. when `~select.epoll` is available,
    always use it instead of `~select.select`), or when a
    previously-monolithic class has been split into specialized
    subclasses.

    Configurable subclasses must define the class methods
    `configurable_base` and `configurable_default`, and use the instance
    method `initialize` instead of ``__init__``.
    """
    __impl_class = None  # type: type
    __impl_kwargs = None  # type: Dict[str, Any]

    def __new__(cls, *args, **kwargs):
        base = cls.configurable_base()
        init_kwargs = {}
        if cls is base:
            impl = cls.configured_class()
            if base.__impl_kwargs:
                init_kwargs.update(base.__impl_kwargs)
        else:
            impl = cls
        init_kwargs.update(kwargs)
        instance = super(Configurable, cls).__new__(impl)
        # initialize vs __init__ chosen for compatibility with AsyncHTTPClient
        # singleton magic.  If we get rid of that we can switch to __init__
        # here too.
        instance.initialize(*args, **init_kwargs)
        return instance

    @classmethod
    def configurable_base(cls):
        # type: () -> Any
        # TODO: This class needs https://github.com/python/typing/issues/107
        # to be fully typeable.
        """Returns the base class of a configurable hierarchy.

        This will normally return the class in which it is defined.
        (which is *not* necessarily the same as the cls classmethod parameter).
        """
        raise NotImplementedError()

    @classmethod
    def configurable_default(cls):
        # type: () -> type
        """Returns the implementation class to be used if none is configured."""
        raise NotImplementedError()

    def initialize(self):
        # type: () -> None
        """Initialize a `Configurable` subclass instance.

        Configurable classes should use `initialize` instead of ``__init__``.

        .. versionchanged:: 4.2
           Now accepts positional arguments in addition to keyword arguments.
        """

    @classmethod
    def configure(cls, impl, **kwargs):
        # type: (Any, **Any) -> None
        """Sets the class to use when the base class is instantiated.

        Keyword arguments will be saved and added to the arguments passed
        to the constructor.  This can be used to set global defaults for
        some parameters.
        """
        base = cls.configurable_base()
        if isinstance(impl, (str, unicode_type)):
            impl = import_object(impl)
        if impl is not None and not issubclass(impl, cls):
            raise ValueError("Invalid subclass of %s" % cls)
        base.__impl_class = impl
        base.__impl_kwargs = kwargs

    @classmethod
    def configured_class(cls):
        # type: () -> type
        """Returns the currently configured class."""
        base = cls.configurable_base()
        if cls.__impl_class is None:
            base.__impl_class = cls.configurable_default()
        return base.__impl_class

    @classmethod
    def _save_configuration(cls):
        # type: () -> Tuple[type, Dict[str, Any]]
        base = cls.configurable_base()
        return (base.__impl_class, base.__impl_kwargs)

    @classmethod
    def _restore_configuration(cls, saved):
        # type: (Tuple[type, Dict[str, Any]]) -> None
        base = cls.configurable_base()
        base.__impl_class = saved[0]
        base.__impl_kwargs = saved[1]


class ArgReplacer(object):
    """Replaces one value in an ``args, kwargs`` pair.

    Inspects the function signature to find an argument by name
    whether it is passed by position or keyword.  For use in decorators
    and similar wrappers.
    """
    def __init__(self, func, name):
        # type: (Callable, str) -> None
        self.name = name
        try:
            self.arg_pos = self._getargnames(func).index(name)
        except ValueError:
            # Not a positional parameter
            self.arg_pos = None

    def _getargnames(self, func):
        # type: (Callable) -> List[str]
        try:
            return getargspec(func).args
        except TypeError:
            if hasattr(func, 'func_code'):
                # Cython-generated code has all the attributes needed
                # by inspect.getargspec, but the inspect module only
                # works with ordinary functions. Inline the portion of
                # getargspec that we need here. Note that for static
                # functions the @cython.binding(True) decorator must
                # be used (for methods it works out of the box).
                code = func.func_code  # type: ignore
                return code.co_varnames[:code.co_argcount]
            raise

    def get_old_value(self, args, kwargs, default=None):
        # type: (List[Any], Dict[str, Any], Any) -> Any
        """Returns the old value of the named argument without replacing it.

        Returns ``default`` if the argument is not present.
        """
        if self.arg_pos is not None and len(args) > self.arg_pos:
            return args[self.arg_pos]
        else:
            return kwargs.get(self.name, default)

    def replace(self, new_value, args, kwargs):
        # type: (Any, List[Any], Dict[str, Any]) -> Tuple[Any, List[Any], Dict[str, Any]]
        """Replace the named argument in ``args, kwargs`` with ``new_value``.

        Returns ``(old_value, args, kwargs)``.  The returned ``args`` and
        ``kwargs`` objects may not be the same as the input objects, or
        the input objects may be mutated.

        If the named argument was not found, ``new_value`` will be added
        to ``kwargs`` and None will be returned as ``old_value``.
        """
        if self.arg_pos is not None and len(args) > self.arg_pos:
            # The arg to replace is passed positionally
            old_value = args[self.arg_pos]
            args = list(args)  # *args is normally a tuple
            args[self.arg_pos] = new_value
        else:
            # The arg to replace is either omitted or passed by keyword.
            old_value = kwargs.get(self.name)
            kwargs[self.name] = new_value
        return old_value, args, kwargs


def timedelta_to_seconds(td):
    # type: (datetime.timedelta) -> float
    """Equivalent to td.total_seconds() (introduced in python 2.7)."""
    return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / float(10 ** 6)


def _websocket_mask_python(mask, data):
    # type: (bytes, bytes) -> bytes
    """Websocket masking function.

    `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length.
    Returns a `bytes` object of the same length as `data` with the mask applied
    as specified in section 5.3 of RFC 6455.

    This pure-python implementation may be replaced by an optimized version when available.
    """
    mask_arr = array.array("B", mask)
    unmasked_arr = array.array("B", data)
    for i in xrange(len(data)):
        unmasked_arr[i] = unmasked_arr[i] ^ mask_arr[i % 4]
    if PY3:
        # tostring was deprecated in py32.  It hasn't been removed,
        # but since we turn on deprecation warnings in our tests
        # we need to use the right one.
        return unmasked_arr.tobytes()
    else:
        return unmasked_arr.tostring()


if (os.environ.get('TORNADO_NO_EXTENSION') or
        os.environ.get('TORNADO_EXTENSION') == '0'):
    # These environment variables exist to make it easier to do performance
    # comparisons; they are not guaranteed to remain supported in the future.
    _websocket_mask = _websocket_mask_python
else:
    try:
        from tornado.speedups import websocket_mask as _websocket_mask
    except ImportError:
        if os.environ.get('TORNADO_EXTENSION') == '1':
            raise
        _websocket_mask = _websocket_mask_python


def doctests():
    import doctest
    return doctest.DocTestSuite()

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
[ISSUE]
**Title:** Initialization Fails with Unexpected Keyword Argument When Using Multiple Configurable Bases

**Description:**
When configuring classes with multiple configurable bases, initializing an instance with specific keyword arguments results in a `TypeError`. This occurs because the initialization process does not correctly handle passing arguments through the hierarchy of configurable bases.

**Example:**
Consider the following configuration setup:

```python
class TestConfig3(TestConfigurable):
    @classmethod
    def configurable_base(cls):
        return TestConfig3

    @classmethod
    def configurable_default(cls):
        return TestConfig3A

class TestConfig3A(TestConfig3):
    def initialize(self, a=None):
        self.a = a

class TestConfig3B(TestConfig3):
    def initialize(self, b=None):
        self.b = b

# Configuration attempt
TestConfigurable.configure(TestConfig3, a=1)
obj = TestConfigurable()
```

**Expected Behavior:**
Initializing `TestConfigurable` with `a=1` should create an instance of `TestConfig3A` with the attribute `a` set to `1`.

**Actual Behavior:**
A `TypeError` is raised:
```
TypeError: initialize() got an unexpected keyword argument 'a'
```
This error indicates that the `initialize` method does not accept the keyword argument `a` when multiple configurable bases are involved.

[/ISSUE]
{
    "ArgReplacerTest.test_keyword": "PASSED",
    "ArgReplacerTest.test_omitted": "PASSED",
    "ArgReplacerTest.test_position": "PASSED",
    "ConfigurableTest.test_config_args": "PASSED",
    "ConfigurableTest.test_config_class": "PASSED",
    "ConfigurableTest.test_config_class_args": "PASSED",
    "ConfigurableTest.test_config_inner_level": "PASSED",
    "ConfigurableTest.test_config_multi_level": "PASSED",
    "ConfigurableTest.test_default": "PASSED",
    "ImportObjectTest.test_import_member": "PASSED",
    "ImportObjectTest.test_import_member_unicode": "PASSED",
    "ImportObjectTest.test_import_module": "PASSED",
    "ImportObjectTest.test_import_module_unicode": "PASSED",
    "IsFinalizingTest.test_basic": "PASSED",
    "RaiseExcInfoTest.test_two_arg_exception": "PASSED",
    "ReUnescapeTest.test_re_unescape": "PASSED",
    "ReUnescapeTest.test_re_unescape_raises_error_on_invalid_input": "PASSED",
    "TimedeltaToSecondsTest.test_timedelta_to_seconds": "PASSED",
    "UnicodeLiteralTest.test_unicode_escapes": "PASSED"
}
diff --git a/tornado/util.py b/tornado/util.py
index 981b94c8..bfd80beb 100644
--- a/tornado/util.py
+++ b/tornado/util.py
@@ -286,6 +286,9 @@ class Configurable(object):
         else:
             impl = cls
         init_kwargs.update(kwargs)
+        if impl.configurable_base() is not base:
+            # The impl class is itself configurable, so recurse.
+            return impl(*args, **init_kwargs)
         instance = super(Configurable, cls).__new__(impl)
         # initialize vs __init__ chosen for compatibility with AsyncHTTPClient
         # singleton magic.  If we get rid of that we can switch to __init__
@@ -343,7 +346,10 @@ class Configurable(object):
         # type: () -> type
         """Returns the currently configured class."""
         base = cls.configurable_base()
-        if cls.__impl_class is None:
+        # Manually mangle the private name to see whether this base
+        # has been configured (and not another base higher in the
+        # hierarchy).
+        if base.__dict__.get('_Configurable__impl_class') is None:
             base.__impl_class = cls.configurable_default()
         return base.__impl_class
 
 

{"tornado/util.py": "\"\"\"Miscellaneous utility functions and classes.\n\nThis module is used internally by Tornado.  It is not necessarily expected\nthat the functions and classes defined here will be useful to other\napplications, but they are documented here in case they are.\n\nThe one public-facing part of this module is the `Configurable` class\nand its `~Configurable.configure` method, which becomes a part of the\ninterface of its subclasses, including `.AsyncHTTPClient`, `.IOLoop`,\nand `.Resolver`.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nimport array\nimport atexit\nimport os\nimport re\nimport sys\nimport zlib\n\nPY3 = sys.version_info >= (3,)\n\nif PY3:\n    xrange = range\n\n# inspect.getargspec() raises DeprecationWarnings in Python 3.5.\n# The two functions have compatible interfaces for the parts we need.\nif PY3:\n    from inspect import getfullargspec as getargspec\nelse:\n    from inspect import getargspec\n\n# Aliases for types that are spelled differently in different Python\n# versions. bytes_type is deprecated and no longer used in Tornado\n# itself but is left in case anyone outside Tornado is using it.\nbytes_type = bytes\nif PY3:\n    unicode_type = str\n    basestring_type = str\nelse:\n    # The names unicode and basestring don't exist in py3 so silence flake8.\n    unicode_type = unicode  # noqa\n    basestring_type = basestring  # noqa\n\n\ntry:\n    import typing  # noqa\n    from typing import cast\n\n    _ObjectDictBase = typing.Dict[str, typing.Any]\nexcept ImportError:\n    _ObjectDictBase = dict\n\n    def cast(typ, x):\n        return x\nelse:\n    # More imports that are only needed in type comments.\n    import datetime  # noqa\n    import types  # noqa\n    from typing import Any, AnyStr, Union, Optional, Dict, Mapping  # noqa\n    from typing import Tuple, Match, Callable  # noqa\n\n    if PY3:\n        _BaseString = str\n    else:\n        _BaseString = Union[bytes, unicode_type]\n\n\ntry:\n    from sys import is_finalizing\nexcept ImportError:\n    # Emulate it\n    def _get_emulated_is_finalizing():\n        L = []\n        atexit.register(lambda: L.append(None))\n\n        def is_finalizing():\n            # Not referencing any globals here\n            return L != []\n\n        return is_finalizing\n\n    is_finalizing = _get_emulated_is_finalizing()\n\n\nclass ObjectDict(_ObjectDictBase):\n    \"\"\"Makes a dictionary behave like an object, with attribute-style access.\n    \"\"\"\n    def __getattr__(self, name):\n        # type: (str) -> Any\n        try:\n            return self[name]\n        except KeyError:\n            raise AttributeError(name)\n\n    def __setattr__(self, name, value):\n        # type: (str, Any) -> None\n        self[name] = value\n\n\nclass GzipDecompressor(object):\n    \"\"\"Streaming gzip decompressor.\n\n    The interface is like that of `zlib.decompressobj` (without some of the\n    optional arguments, but it understands gzip headers and checksums.\n    \"\"\"\n    def __init__(self):\n        # Magic parameter makes zlib module understand gzip header\n        # http://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib\n        # This works on cpython and pypy, but not jython.\n        self.decompressobj = zlib.decompressobj(16 + zlib.MAX_WBITS)\n\n    def decompress(self, value, max_length=None):\n        # type: (bytes, Optional[int]) -> bytes\n        \"\"\"Decompress a chunk, returning newly-available data.\n\n        Some data may be buffered for later processing; `flush` must\n        be called when there is no more input data to ensure that\n        all data was processed.\n\n        If ``max_length`` is given, some input data may be left over\n        in ``unconsumed_tail``; you must retrieve this value and pass\n        it back to a future call to `decompress` if it is not empty.\n        \"\"\"\n        return self.decompressobj.decompress(value, max_length)\n\n    @property\n    def unconsumed_tail(self):\n        # type: () -> bytes\n        \"\"\"Returns the unconsumed portion left over\n        \"\"\"\n        return self.decompressobj.unconsumed_tail\n\n    def flush(self):\n        # type: () -> bytes\n        \"\"\"Return any remaining buffered data not yet returned by decompress.\n\n        Also checks for errors such as truncated input.\n        No other methods may be called on this object after `flush`.\n        \"\"\"\n        return self.decompressobj.flush()\n\n\ndef import_object(name):\n    # type: (_BaseString) -> Any\n    \"\"\"Imports an object by name.\n\n    import_object('x') is equivalent to 'import x'.\n    import_object('x.y.z') is equivalent to 'from x.y import z'.\n\n    >>> import tornado.escape\n    >>> import_object('tornado.escape') is tornado.escape\n    True\n    >>> import_object('tornado.escape.utf8') is tornado.escape.utf8\n    True\n    >>> import_object('tornado') is tornado\n    True\n    >>> import_object('tornado.missing_module')\n    Traceback (most recent call last):\n        ...\n    ImportError: No module named missing_module\n    \"\"\"\n    if not isinstance(name, str):\n        # on python 2 a byte string is required.\n        name = name.encode('utf-8')\n    if name.count('.') == 0:\n        return __import__(name, None, None)\n\n    parts = name.split('.')\n    obj = __import__('.'.join(parts[:-1]), None, None, [parts[-1]], 0)\n    try:\n        return getattr(obj, parts[-1])\n    except AttributeError:\n        raise ImportError(\"No module named %s\" % parts[-1])\n\n\n# Stubs to make mypy happy (and later for actual type-checking).\ndef raise_exc_info(exc_info):\n    # type: (Tuple[type, BaseException, types.TracebackType]) -> None\n    pass\n\n\ndef exec_in(code, glob, loc=None):\n    # type: (Any, Dict[str, Any], Optional[Mapping[str, Any]]) -> Any\n    if isinstance(code, basestring_type):\n        # exec(string) inherits the caller's future imports; compile\n        # the string first to prevent that.\n        code = compile(code, '<string>', 'exec', dont_inherit=True)\n    exec(code, glob, loc)\n\n\nif PY3:\n    exec(\"\"\"\ndef raise_exc_info(exc_info):\n    try:\n        raise exc_info[1].with_traceback(exc_info[2])\n    finally:\n        exc_info = None\n\n\"\"\")\nelse:\n    exec(\"\"\"\ndef raise_exc_info(exc_info):\n    raise exc_info[0], exc_info[1], exc_info[2]\n\"\"\")\n\n\ndef errno_from_exception(e):\n    # type: (BaseException) -> Optional[int]\n    \"\"\"Provides the errno from an Exception object.\n\n    There are cases that the errno attribute was not set so we pull\n    the errno out of the args but if someone instantiates an Exception\n    without any args you will get a tuple error. So this function\n    abstracts all that behavior to give you a safe way to get the\n    errno.\n    \"\"\"\n\n    if hasattr(e, 'errno'):\n        return e.errno  # type: ignore\n    elif e.args:\n        return e.args[0]\n    else:\n        return None\n\n\n_alphanum = frozenset(\n    \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\")\n\n\ndef _re_unescape_replacement(match):\n    # type: (Match[str]) -> str\n    group = match.group(1)\n    if group[0] in _alphanum:\n        raise ValueError(\"cannot unescape '\\\\\\\\%s'\" % group[0])\n    return group\n\n\n_re_unescape_pattern = re.compile(r'\\\\(.)', re.DOTALL)\n\n\ndef re_unescape(s):\n    # type: (str) -> str\n    \"\"\"Unescape a string escaped by `re.escape`.\n\n    May raise ``ValueError`` for regular expressions which could not\n    have been produced by `re.escape` (for example, strings containing\n    ``\\d`` cannot be unescaped).\n\n    .. versionadded:: 4.4\n    \"\"\"\n    return _re_unescape_pattern.sub(_re_unescape_replacement, s)\n\n\nclass Configurable(object):\n    \"\"\"Base class for configurable interfaces.\n\n    A configurable interface is an (abstract) class whose constructor\n    acts as a factory function for one of its implementation subclasses.\n    The implementation subclass as well as optional keyword arguments to\n    its initializer can be set globally at runtime with `configure`.\n\n    By using the constructor as the factory method, the interface\n    looks like a normal class, `isinstance` works as usual, etc.  This\n    pattern is most useful when the choice of implementation is likely\n    to be a global decision (e.g. when `~select.epoll` is available,\n    always use it instead of `~select.select`), or when a\n    previously-monolithic class has been split into specialized\n    subclasses.\n\n    Configurable subclasses must define the class methods\n    `configurable_base` and `configurable_default`, and use the instance\n    method `initialize` instead of ``__init__``.\n    \"\"\"\n    __impl_class = None  # type: type\n    __impl_kwargs = None  # type: Dict[str, Any]\n\n    def __new__(cls, *args, **kwargs):\n        base = cls.configurable_base()\n        init_kwargs = {}\n        if cls is base:\n            impl = cls.configured_class()\n            if base.__impl_kwargs:\n                init_kwargs.update(base.__impl_kwargs)\n        else:\n            impl = cls\n        init_kwargs.update(kwargs)\n        instance = super(Configurable, cls).__new__(impl)\n        # initialize vs __init__ chosen for compatibility with AsyncHTTPClient\n        # singleton magic.  If we get rid of that we can switch to __init__\n        # here too.\n        instance.initialize(*args, **init_kwargs)\n        return instance\n\n    @classmethod\n    def configurable_base(cls):\n        # type: () -> Any\n        # TODO: This class needs https://github.com/python/typing/issues/107\n        # to be fully typeable.\n        \"\"\"Returns the base class of a configurable hierarchy.\n\n        This will normally return the class in which it is defined.\n        (which is *not* necessarily the same as the cls classmethod parameter).\n        \"\"\"\n        raise NotImplementedError()\n\n    @classmethod\n    def configurable_default(cls):\n        # type: () -> type\n        \"\"\"Returns the implementation class to be used if none is configured.\"\"\"\n        raise NotImplementedError()\n\n    def initialize(self):\n        # type: () -> None\n        \"\"\"Initialize a `Configurable` subclass instance.\n\n        Configurable classes should use `initialize` instead of ``__init__``.\n\n        .. versionchanged:: 4.2\n           Now accepts positional arguments in addition to keyword arguments.\n        \"\"\"\n\n    @classmethod\n    def configure(cls, impl, **kwargs):\n        # type: (Any, **Any) -> None\n        \"\"\"Sets the class to use when the base class is instantiated.\n\n        Keyword arguments will be saved and added to the arguments passed\n        to the constructor.  This can be used to set global defaults for\n        some parameters.\n        \"\"\"\n        base = cls.configurable_base()\n        if isinstance(impl, (str, unicode_type)):\n            impl = import_object(impl)\n        if impl is not None and not issubclass(impl, cls):\n            raise ValueError(\"Invalid subclass of %s\" % cls)\n        base.__impl_class = impl\n        base.__impl_kwargs = kwargs\n\n    @classmethod\n    def configured_class(cls):\n        # type: () -> type\n        \"\"\"Returns the currently configured class.\"\"\"\n        base = cls.configurable_base()\n        if cls.__impl_class is None:\n            base.__impl_class = cls.configurable_default()\n        return base.__impl_class\n\n    @classmethod\n    def _save_configuration(cls):\n        # type: () -> Tuple[type, Dict[str, Any]]\n        base = cls.configurable_base()\n        return (base.__impl_class, base.__impl_kwargs)\n\n    @classmethod\n    def _restore_configuration(cls, saved):\n        # type: (Tuple[type, Dict[str, Any]]) -> None\n        base = cls.configurable_base()\n        base.__impl_class = saved[0]\n        base.__impl_kwargs = saved[1]\n\n\nclass ArgReplacer(object):\n    \"\"\"Replaces one value in an ``args, kwargs`` pair.\n\n    Inspects the function signature to find an argument by name\n    whether it is passed by position or keyword.  For use in decorators\n    and similar wrappers.\n    \"\"\"\n    def __init__(self, func, name):\n        # type: (Callable, str) -> None\n        self.name = name\n        try:\n            self.arg_pos = self._getargnames(func).index(name)\n        except ValueError:\n            # Not a positional parameter\n            self.arg_pos = None\n\n    def _getargnames(self, func):\n        # type: (Callable) -> List[str]\n        try:\n            return getargspec(func).args\n        except TypeError:\n            if hasattr(func, 'func_code'):\n                # Cython-generated code has all the attributes needed\n                # by inspect.getargspec, but the inspect module only\n                # works with ordinary functions. Inline the portion of\n                # getargspec that we need here. Note that for static\n                # functions the @cython.binding(True) decorator must\n                # be used (for methods it works out of the box).\n                code = func.func_code  # type: ignore\n                return code.co_varnames[:code.co_argcount]\n            raise\n\n    def get_old_value(self, args, kwargs, default=None):\n        # type: (List[Any], Dict[str, Any], Any) -> Any\n        \"\"\"Returns the old value of the named argument without replacing it.\n\n        Returns ``default`` if the argument is not present.\n        \"\"\"\n        if self.arg_pos is not None and len(args) > self.arg_pos:\n            return args[self.arg_pos]\n        else:\n            return kwargs.get(self.name, default)\n\n    def replace(self, new_value, args, kwargs):\n        # type: (Any, List[Any], Dict[str, Any]) -> Tuple[Any, List[Any], Dict[str, Any]]\n        \"\"\"Replace the named argument in ``args, kwargs`` with ``new_value``.\n\n        Returns ``(old_value, args, kwargs)``.  The returned ``args`` and\n        ``kwargs`` objects may not be the same as the input objects, or\n        the input objects may be mutated.\n\n        If the named argument was not found, ``new_value`` will be added\n        to ``kwargs`` and None will be returned as ``old_value``.\n        \"\"\"\n        if self.arg_pos is not None and len(args) > self.arg_pos:\n            # The arg to replace is passed positionally\n            old_value = args[self.arg_pos]\n            args = list(args)  # *args is normally a tuple\n            args[self.arg_pos] = new_value\n        else:\n            # The arg to replace is either omitted or passed by keyword.\n            old_value = kwargs.get(self.name)\n            kwargs[self.name] = new_value\n        return old_value, args, kwargs\n\n\ndef timedelta_to_seconds(td):\n    # type: (datetime.timedelta) -> float\n    \"\"\"Equivalent to td.total_seconds() (introduced in python 2.7).\"\"\"\n    return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / float(10 ** 6)\n\n\ndef _websocket_mask_python(mask, data):\n    # type: (bytes, bytes) -> bytes\n    \"\"\"Websocket masking function.\n\n    `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length.\n    Returns a `bytes` object of the same length as `data` with the mask applied\n    as specified in section 5.3 of RFC 6455.\n\n    This pure-python implementation may be replaced by an optimized version when available.\n    \"\"\"\n    mask_arr = array.array(\"B\", mask)\n    unmasked_arr = array.array(\"B\", data)\n    for i in xrange(len(data)):\n        unmasked_arr[i] = unmasked_arr[i] ^ mask_arr[i % 4]\n    if PY3:\n        # tostring was deprecated in py32.  It hasn't been removed,\n        # but since we turn on deprecation warnings in our tests\n        # we need to use the right one.\n        return unmasked_arr.tobytes()\n    else:\n        return unmasked_arr.tostring()\n\n\nif (os.environ.get('TORNADO_NO_EXTENSION') or\n        os.environ.get('TORNADO_EXTENSION') == '0'):\n    # These environment variables exist to make it easier to do performance\n    # comparisons; they are not guaranteed to remain supported in the future.\n    _websocket_mask = _websocket_mask_python\nelse:\n    try:\n        from tornado.speedups import websocket_mask as _websocket_mask\n    except ImportError:\n        if os.environ.get('TORNADO_EXTENSION') == '1':\n            raise\n        _websocket_mask = _websocket_mask_python\n\n\ndef doctests():\n    import doctest\n    return doctest.DocTestSuite()\n"}
A user will ask you to solve a task. You should first draft your thinking process (inner monologue). Then, generate the solution.

Your response format must follow the template below:
<think>
Your thoughts or/and draft, like working through an exercise on scratch paper. Be as casual and as long as you want until you are confident to generate a correct solution.
</think>
<solution>
Final solution presented to the user.
</solution>
system
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** Initialization Fails with Unexpected Keyword Argument When Using Multiple Configurable Bases

**Description:**
When configuring classes with multiple configurable bases, initializing an instance with specific keyword arguments results in a `TypeError`. This occurs because the initialization process does not correctly handle passing arguments through the hierarchy of configurable bases.

**Example:**
Consider the following configuration setup:

```python
class TestConfig3(TestConfigurable):
    @classmethod
    def configurable_base(cls):
        return TestConfig3

    @classmethod
    def configurable_default(cls):
        return TestConfig3A

class TestConfig3A(TestConfig3):
    def initialize(self, a=None):
        self.a = a

class TestConfig3B(TestConfig3):
    def initialize(self, b=None):
        self.b = b

# Configuration attempt
TestConfigurable.configure(TestConfig3, a=1)
obj = TestConfigurable()
```

**Expected Behavior:**
Initializing `TestConfigurable` with `a=1` should create an instance of `TestConfig3A` with the attribute `a` set to `1`.

**Actual Behavior:**
A `TypeError` is raised:
```
TypeError: initialize() got an unexpected keyword argument 'a'
```
This error indicates that the `initialize` method does not accept the keyword argument `a` when multiple configurable bases are involved.

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### tornado/util.py
"""Miscellaneous utility functions and classes.

This module is used internally by Tornado.  It is not necessarily expected
that the functions and classes defined here will be useful to other
applications, but they are documented here in case they are.

The one public-facing part of this module is the `Configurable` class
and its `~Configurable.configure` method, which becomes a part of the
interface of its subclasses, including `.AsyncHTTPClient`, `.IOLoop`,
and `.Resolver`.
"""

from __future__ import absolute_import, division, print_function

import array
import atexit
import os
import re
import sys
import zlib

PY3 = sys.version_info >= (3,)

if PY3:
    xrange = range

# inspect.getargspec() raises DeprecationWarnings in Python 3.5.
# The two functions have compatible interfaces for the parts we need.
if PY3:
    from inspect import getfullargspec as getargspec
else:
    from inspect import getargspec

# Aliases for types that are spelled differently in different Python
# versions. bytes_type is deprecated and no longer used in Tornado
# itself but is left in case anyone outside Tornado is using it.
bytes_type = bytes
if PY3:
    unicode_type = str
    basestring_type = str
else:
    # The names unicode and basestring don't exist in py3 so silence flake8.
    unicode_type = unicode  # noqa
    basestring_type = basestring  # noqa


try:
    import typing  # noqa
    from typing import cast

    _ObjectDictBase = typing.Dict[str, typing.Any]
except ImportError:
    _ObjectDictBase = dict

    def cast(typ, x):
        return x
else:
    # More imports that are only needed in type comments.
    import datetime  # noqa
    import types  # noqa
    from typing import Any, AnyStr, Union, Optional, Dict, Mapping  # noqa
    from typing import Tuple, Match, Callable  # noqa

    if PY3:
        _BaseString = str
    else:
        _BaseString = Union[bytes, unicode_type]


try:
    from sys import is_finalizing
except ImportError:
    # Emulate it
    def _get_emulated_is_finalizing():
        L = []
        atexit.register(lambda: L.append(None))

        def is_finalizing():
            # Not referencing any globals here
            return L != []

        return is_finalizing

    is_finalizing = _get_emulated_is_finalizing()


class ObjectDict(_ObjectDictBase):
    """Makes a dictionary behave like an object, with attribute-style access.
    """
    def __getattr__(self, name):
        # type: (str) -> Any
        try:
            return self[name]
        except KeyError:
            raise AttributeError(name)

    def __setattr__(self, name, value):
        # type: (str, Any) -> None
        self[name] = value


class GzipDecompressor(object):
    """Streaming gzip decompressor.

    The interface is like that of `zlib.decompressobj` (without some of the
    optional arguments, but it understands gzip headers and checksums.
    """
    def __init__(self):
        # Magic parameter makes zlib module understand gzip header
        # http://stackoverflow.com/questions/1838699/how-can-i-decompress-a-gzip-stream-with-zlib
        # This works on cpython and pypy, but not jython.
        self.decompressobj = zlib.decompressobj(16 + zlib.MAX_WBITS)

    def decompress(self, value, max_length=None):
        # type: (bytes, Optional[int]) -> bytes
        """Decompress a chunk, returning newly-available data.

        Some data may be buffered for later processing; `flush` must
        be called when there is no more input data to ensure that
        all data was processed.

        If ``max_length`` is given, some input data may be left over
        in ``unconsumed_tail``; you must retrieve this value and pass
        it back to a future call to `decompress` if it is not empty.
        """
        return self.decompressobj.decompress(value, max_length)

    @property
    def unconsumed_tail(self):
        # type: () -> bytes
        """Returns the unconsumed portion left over
        """
        return self.decompressobj.unconsumed_tail

    def flush(self):
        # type: () -> bytes
        """Return any remaining buffered data not yet returned by decompress.

        Also checks for errors such as truncated input.
        No other methods may be called on this object after `flush`.
        """
        return self.decompressobj.flush()


def import_object(name):
    # type: (_BaseString) -> Any
    """Imports an object by name.

    import_object('x') is equivalent to 'import x'.
    import_object('x.y.z') is equivalent to 'from x.y import z'.

    >>> import tornado.escape
    >>> import_object('tornado.escape') is tornado.escape
    True
    >>> import_object('tornado.escape.utf8') is tornado.escape.utf8
    True
    >>> import_object('tornado') is tornado
    True
    >>> import_object('tornado.missing_module')
    Traceback (most recent call last):
        ...
    ImportError: No module named missing_module
    """
    if not isinstance(name, str):
        # on python 2 a byte string is required.
        name = name.encode('utf-8')
    if name.count('.') == 0:
        return __import__(name, None, None)

    parts = name.split('.')
    obj = __import__('.'.join(parts[:-1]), None, None, [parts[-1]], 0)
    try:
        return getattr(obj, parts[-1])
    except AttributeError:
        raise ImportError("No module named %s" % parts[-1])


# Stubs to make mypy happy (and later for actual type-checking).
def raise_exc_info(exc_info):
    # type: (Tuple[type, BaseException, types.TracebackType]) -> None
    pass


def exec_in(code, glob, loc=None):
    # type: (Any, Dict[str, Any], Optional[Mapping[str, Any]]) -> Any
    if isinstance(code, basestring_type):
        # exec(string) inherits the caller's future imports; compile
        # the string first to prevent that.
        code = compile(code, '<string>', 'exec', dont_inherit=True)
    exec(code, glob, loc)


if PY3:
    exec("""
def raise_exc_info(exc_info):
    try:
        raise exc_info[1].with_traceback(exc_info[2])
    finally:
        exc_info = None

""")
else:
    exec("""
def raise_exc_info(exc_info):
    raise exc_info[0], exc_info[1], exc_info[2]
""")


def errno_from_exception(e):
    # type: (BaseException) -> Optional[int]
    """Provides the errno from an Exception object.

    There are cases that the errno attribute was not set so we pull
    the errno out of the args but if someone instantiates an Exception
    without any args you will get a tuple error. So this function
    abstracts all that behavior to give you a safe way to get the
    errno.
    """

    if hasattr(e, 'errno'):
        return e.errno  # type: ignore
    elif e.args:
        return e.args[0]
    else:
        return None


_alphanum = frozenset(
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")


def _re_unescape_replacement(match):
    # type: (Match[str]) -> str
    group = match.group(1)
    if group[0] in _alphanum:
        raise ValueError("cannot unescape '\\\\%s'" % group[0])
    return group


_re_unescape_pattern = re.compile(r'\\(.)', re.DOTALL)


def re_unescape(s):
    # type: (str) -> str
    """Unescape a string escaped by `re.escape`.

    May raise ``ValueError`` for regular expressions which could not
    have been produced by `re.escape` (for example, strings containing
    ``\d`` cannot be unescaped).

    .. versionadded:: 4.4
    """
    return _re_unescape_pattern.sub(_re_unescape_replacement, s)


class Configurable(object):
    """Base class for configurable interfaces.

    A configurable interface is an (abstract) class whose constructor
    acts as a factory function for one of its implementation subclasses.
    The implementation subclass as well as optional keyword arguments to
    its initializer can be set globally at runtime with `configure`.

    By using the constructor as the factory method, the interface
    looks like a normal class, `isinstance` works as usual, etc.  This
    pattern is most useful when the choice of implementation is likely
    to be a global decision (e.g. when `~select.epoll` is available,
    always use it instead of `~select.select`), or when a
    previously-monolithic class has been split into specialized
    subclasses.

    Configurable subclasses must define the class methods
    `configurable_base` and `configurable_default`, and use the instance
    method `initialize` instead of ``__init__``.
    """
    __impl_class = None  # type: type
    __impl_kwargs = None  # type: Dict[str, Any]

    def __new__(cls, *args, **kwargs):
        base = cls.configurable_base()
        init_kwargs = {}
        if cls is base:
            impl = cls.configured_class()
            if base.__impl_kwargs:
                init_kwargs.update(base.__impl_kwargs)
        else:
            impl = cls
        init_kwargs.update(kwargs)
        instance = super(Configurable, cls).__new__(impl)
        # initialize vs __init__ chosen for compatibility with AsyncHTTPClient
        # singleton magic.  If we get rid of that we can switch to __init__
        # here too.
        instance.initialize(*args, **init_kwargs)
        return instance

    @classmethod
    def configurable_base(cls):
        # type: () -> Any
        # TODO: This class needs https://github.com/python/typing/issues/107
        # to be fully typeable.
        """Returns the base class of a configurable hierarchy.

        This will normally return the class in which it is defined.
        (which is *not* necessarily the same as the cls classmethod parameter).
        """
        raise NotImplementedError()

    @classmethod
    def configurable_default(cls):
        # type: () -> type
        """Returns the implementation class to be used if none is configured."""
        raise NotImplementedError()

    def initialize(self):
        # type: () -> None
        """Initialize a `Configurable` subclass instance.

        Configurable classes should use `initialize` instead of ``__init__``.

        .. versionchanged:: 4.2
           Now accepts positional arguments in addition to keyword arguments.
        """

    @classmethod
    def configure(cls, impl, **kwargs):
        # type: (Any, **Any) -> None
        """Sets the class to use when the base class is instantiated.

        Keyword arguments will be saved and added to the arguments passed
        to the constructor.  This can be used to set global defaults for
        some parameters.
        """
        base = cls.configurable_base()
        if isinstance(impl, (str, unicode_type)):
            impl = import_object(impl)
        if impl is not None and not issubclass(impl, cls):
            raise ValueError("Invalid subclass of %s" % cls)
        base.__impl_class = impl
        base.__impl_kwargs = kwargs

    @classmethod
    def configured_class(cls):
        # type: () -> type
        """Returns the currently configured class."""
        base = cls.configurable_base()
        if cls.__impl_class is None:
            base.__impl_class = cls.configurable_default()
        return base.__impl_class

    @classmethod
    def _save_configuration(cls):
        # type: () -> Tuple[type, Dict[str, Any]]
        base = cls.configurable_base()
        return (base.__impl_class, base.__impl_kwargs)

    @classmethod
    def _restore_configuration(cls, saved):
        # type: (Tuple[type, Dict[str, Any]]) -> None
        base = cls.configurable_base()
        base.__impl_class = saved[0]
        base.__impl_kwargs = saved[1]


class ArgReplacer(object):
    """Replaces one value in an ``args, kwargs`` pair.

    Inspects the function signature to find an argument by name
    whether it is passed by position or keyword.  For use in decorators
    and similar wrappers.
    """
    def __init__(self, func, name):
        # type: (Callable, str) -> None
        self.name = name
        try:
            self.arg_pos = self._getargnames(func).index(name)
        except ValueError:
            # Not a positional parameter
            self.arg_pos = None

    def _getargnames(self, func):
        # type: (Callable) -> List[str]
        try:
            return getargspec(func).args
        except TypeError:
            if hasattr(func, 'func_code'):
                # Cython-generated code has all the attributes needed
                # by inspect.getargspec, but the inspect module only
                # works with ordinary functions. Inline the portion of
                # getargspec that we need here. Note that for static
                # functions the @cython.binding(True) decorator must
                # be used (for methods it works out of the box).
                code = func.func_code  # type: ignore
                return code.co_varnames[:code.co_argcount]
            raise

    def get_old_value(self, args, kwargs, default=None):
        # type: (List[Any], Dict[str, Any], Any) -> Any
        """Returns the old value of the named argument without replacing it.

        Returns ``default`` if the argument is not present.
        """
        if self.arg_pos is not None and len(args) > self.arg_pos:
            return args[self.arg_pos]
        else:
            return kwargs.get(self.name, default)

    def replace(self, new_value, args, kwargs):
        # type: (Any, List[Any], Dict[str, Any]) -> Tuple[Any, List[Any], Dict[str, Any]]
        """Replace the named argument in ``args, kwargs`` with ``new_value``.

        Returns ``(old_value, args, kwargs)``.  The returned ``args`` and
        ``kwargs`` objects may not be the same as the input objects, or
        the input objects may be mutated.

        If the named argument was not found, ``new_value`` will be added
        to ``kwargs`` and None will be returned as ``old_value``.
        """
        if self.arg_pos is not None and len(args) > self.arg_pos:
            # The arg to replace is passed positionally
            old_value = args[self.arg_pos]
            args = list(args)  # *args is normally a tuple
            args[self.arg_pos] = new_value
        else:
            # The arg to replace is either omitted or passed by keyword.
            old_value = kwargs.get(self.name)
            kwargs[self.name] = new_value
        return old_value, args, kwargs


def timedelta_to_seconds(td):
    # type: (datetime.timedelta) -> float
    """Equivalent to td.total_seconds() (introduced in python 2.7)."""
    return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / float(10 ** 6)


def _websocket_mask_python(mask, data):
    # type: (bytes, bytes) -> bytes
    """Websocket masking function.

    `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length.
    Returns a `bytes` object of the same length as `data` with the mask applied
    as specified in section 5.3 of RFC 6455.

    This pure-python implementation may be replaced by an optimized version when available.
    """
    mask_arr = array.array("B", mask)
    unmasked_arr = array.array("B", data)
    for i in xrange(len(data)):
        unmasked_arr[i] = unmasked_arr[i] ^ mask_arr[i % 4]
    if PY3:
        # tostring was deprecated in py32.  It hasn't been removed,
        # but since we turn on deprecation warnings in our tests
        # we need to use the right one.
        return unmasked_arr.tobytes()
    else:
        return unmasked_arr.tostring()


if (os.environ.get('TORNADO_NO_EXTENSION') or
        os.environ.get('TORNADO_EXTENSION') == '0'):
    # These environment variables exist to make it easier to do performance
    # comparisons; they are not guaranteed to remain supported in the future.
    _websocket_mask = _websocket_mask_python
else:
    try:
        from tornado.speedups import websocket_mask as _websocket_mask
    except ImportError:
        if os.environ.get('TORNADO_EXTENSION') == '1':
            raise
        _websocket_mask = _websocket_mask_python


def doctests():
    import doctest
    return doctest.DocTestSuite()

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
user