{
    "file_diffs": [
        {
            "old_file_content": "# coding: utf-8\nfrom __future__ import absolute_import, division, print_function, with_statement\nimport sys\nimport datetime\n\nimport tornado.escape\nfrom tornado.escape import utf8\nfrom tornado.util import raise_exc_info, Configurable, u, exec_in, ArgReplacer, timedelta_to_seconds, import_object\nfrom tornado.test.util import unittest\n\ntry:\n    from cStringIO import StringIO  # py2\nexcept ImportError:\n    from io import StringIO  # py3\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, a=None):\n        self.a = a\n\n\nclass TestConfig2(TestConfigurable):\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\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(a=4)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 4)\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(b=6)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 6)\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",
            "new_file_content": "# coding: utf-8\nfrom __future__ import absolute_import, division, print_function, with_statement\nimport sys\nimport datetime\n\nimport tornado.escape\nfrom tornado.escape import utf8\nfrom tornado.util import raise_exc_info, Configurable, u, exec_in, ArgReplacer, timedelta_to_seconds, import_object\nfrom tornado.test.util import unittest\n\ntry:\n    from cStringIO import StringIO  # py2\nexcept ImportError:\n    from io import StringIO  # py3\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",
            "header": {
                "file": {
                    "path": "tornado/test/util_test.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "a0fbae43",
                "new_commit_hash": "0936c89a",
                "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": 46,
                            "length": 13
                        },
                        "new_range": {
                            "start": 46,
                            "length": 15
                        },
                        "section": "class TestConfigurable(Configurable):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "class TestConfig1(TestConfigurable):",
                                "type": "context"
                            },
                            {
                                "content": "    def initialize(self, a=None):",
                                "type": "deleted"
                            },
                            {
                                "content": "    def initialize(self, pos_arg=None, a=None):",
                                "type": "added"
                            },
                            {
                                "content": "        self.a = a",
                                "type": "context"
                            },
                            {
                                "content": "        self.pos_arg = pos_arg",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "class TestConfig2(TestConfigurable):",
                                "type": "context"
                            },
                            {
                                "content": "    def initialize(self, b=None):",
                                "type": "deleted"
                            },
                            {
                                "content": "    def initialize(self, pos_arg=None, b=None):",
                                "type": "added"
                            },
                            {
                                "content": "        self.b = b",
                                "type": "context"
                            },
                            {
                                "content": "        self.pos_arg = pos_arg",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "class ConfigurableTest(unittest.TestCase):",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/test/util_test.py",
                            "type": "class",
                            "name": "TestConfig2",
                            "content": "class TestConfig2(TestConfigurable):\n    def initialize(self, b=None):\n        self.b = b",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 53,
                            "end_lineno": 55,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/test/util_test.py",
                            "type": "method",
                            "name": "TestConfig2.initialize",
                            "content": "class TestConfig2(TestConfigurable):\n    def initialize(self, b=None):\n        self.b = b",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 54,
                            "end_lineno": 55,
                            "parent": {
                                "file_name": "tornado/test/util_test.py",
                                "type": "class",
                                "name": "TestConfig2",
                                "content": "class TestConfig2(TestConfigurable):\n    def initialize(self, b=None):\n        self.b = b",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 53,
                                "end_lineno": 55,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/util_test.py",
                            "type": "class",
                            "name": "TestConfig1",
                            "content": "class TestConfig1(TestConfigurable):\n    def initialize(self, a=None):\n        self.a = a",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 48,
                            "end_lineno": 50,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/test/util_test.py",
                            "type": "method",
                            "name": "TestConfig1.initialize",
                            "content": "class TestConfig1(TestConfigurable):\n    def initialize(self, a=None):\n        self.a = a",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 49,
                            "end_lineno": 50,
                            "parent": {
                                "file_name": "tornado/test/util_test.py",
                                "type": "class",
                                "name": "TestConfig1",
                                "content": "class TestConfig1(TestConfigurable):\n    def initialize(self, a=None):\n        self.a = a",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 48,
                                "end_lineno": 50,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 102,
                            "length": 9
                        },
                        "new_range": {
                            "start": 104,
                            "length": 10
                        },
                        "section": "class ConfigurableTest(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        self.assertIsInstance(obj, TestConfig1)",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertEqual(obj.a, 3)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        obj = TestConfigurable(a=4)",
                                "type": "deleted"
                            },
                            {
                                "content": "        obj = TestConfigurable(42, a=4)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertIsInstance(obj, TestConfig1)",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertEqual(obj.a, 4)",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertEqual(obj.pos_arg, 42)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        self.checkSubclasses()",
                                "type": "context"
                            },
                            {
                                "content": "        # args bound in configure don't apply when using the subclass directly",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/test/util_test.py",
                            "type": "method",
                            "name": "ConfigurableTest.test_config_args",
                            "content": "class 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(a=4)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 4)\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(b=6)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 6)\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)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 99,
                            "end_lineno": 112,
                            "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\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(a=4)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 4)\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(b=6)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 6)\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)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 58,
                                "end_lineno": 127,
                                "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\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(a=4)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 4)\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(b=6)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 6)\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)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 58,
                            "end_lineno": 127,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 117,
                            "length": 9
                        },
                        "new_range": {
                            "start": 120,
                            "length": 10
                        },
                        "section": "class ConfigurableTest(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        self.assertIsInstance(obj, TestConfig2)",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertEqual(obj.b, 5)",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        obj = TestConfigurable(b=6)",
                                "type": "deleted"
                            },
                            {
                                "content": "        obj = TestConfigurable(42, b=6)",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertIsInstance(obj, TestConfig2)",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertEqual(obj.b, 6)",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertEqual(obj.pos_arg, 42)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        self.checkSubclasses()",
                                "type": "context"
                            },
                            {
                                "content": "        # args bound in configure don't apply when using the subclass directly",
                                "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\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(a=4)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 4)\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(b=6)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 6)\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)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 58,
                            "end_lineno": 127,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/test/util_test.py",
                            "type": "method",
                            "name": "ConfigurableTest.test_config_class_args",
                            "content": "class 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(a=4)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 4)\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(b=6)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 6)\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)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 114,
                            "end_lineno": 127,
                            "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\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(a=4)\n        self.assertIsInstance(obj, TestConfig1)\n        self.assertEqual(obj.a, 4)\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(b=6)\n        self.assertIsInstance(obj, TestConfig2)\n        self.assertEqual(obj.b, 6)\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)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 58,
                                "end_lineno": 127,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "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, with_statement\n\nimport array\nimport inspect\nimport os\nimport sys\nimport zlib\n\n\ntry:\n    xrange  # py2\nexcept NameError:\n    xrange = range  # py3\n\n\nclass ObjectDict(dict):\n    \"\"\"Makes a dictionary behave like an object, with attribute-style access.\n    \"\"\"\n    def __getattr__(self, name):\n        try:\n            return self[name]\n        except KeyError:\n            raise AttributeError(name)\n\n    def __setattr__(self, name, value):\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        \"\"\"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        \"\"\"Returns the unconsumed portion left over\n        \"\"\"\n        return self.decompressobj.unconsumed_tail\n\n    def flush(self):\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\n# Fake unicode literal support:  Python 3.2 doesn't have the u'' marker for\n# literal strings, and alternative solutions like \"from __future__ import\n# unicode_literals\" have other problems (see PEP 414).  u() can be applied\n# to ascii strings that include \\u escapes (but they must not contain\n# literal non-ascii characters).\nif not isinstance(b'', type('')):\n    def u(s):\n        return s\n    unicode_type = str\n    basestring_type = str\nelse:\n    def u(s):\n        return s.decode('unicode_escape')\n    # These names don't exist in py3, so use noqa comments to disable\n    # warnings in flake8.\n    unicode_type = unicode  # noqa\n    basestring_type = basestring  # noqa\n\n\ndef import_object(name):\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 isinstance(name, unicode_type) and str is not unicode_type:\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# Deprecated alias that was used before we dropped py25 support.\n# Left here in case anyone outside Tornado is using it.\nbytes_type = bytes\n\nif sys.version_info > (3,):\n    exec(\"\"\"\ndef raise_exc_info(exc_info):\n    raise exc_info[1].with_traceback(exc_info[2])\n\ndef exec_in(code, glob, loc=None):\n    if isinstance(code, str):\n        code = compile(code, '<string>', 'exec', dont_inherit=True)\n    exec(code, glob, loc)\n\"\"\")\nelse:\n    exec(\"\"\"\ndef raise_exc_info(exc_info):\n    raise exc_info[0], exc_info[1], exc_info[2]\n\ndef exec_in(code, glob, loc=None):\n    if isinstance(code, basestring):\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 in glob, loc\n\"\"\")\n\n\ndef errno_from_exception(e):\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\n    elif e.args:\n        return e.args[0]\n    else:\n        return None\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\n    __impl_kwargs = None\n\n    def __new__(cls, **kwargs):\n        base = cls.configurable_base()\n        args = {}\n        if cls is base:\n            impl = cls.configured_class()\n            if base.__impl_kwargs:\n                args.update(base.__impl_kwargs)\n        else:\n            impl = cls\n        args.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)\n        return instance\n\n    @classmethod\n    def configurable_base(cls):\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        \"\"\"Returns the implementation class to be used if none is configured.\"\"\"\n        raise NotImplementedError()\n\n    def initialize(self):\n        \"\"\"Initialize a `Configurable` subclass instance.\n\n        Configurable classes should use `initialize` instead of ``__init__``.\n        \"\"\"\n\n    @classmethod\n    def configure(cls, impl, **kwargs):\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, (unicode_type, bytes)):\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        \"\"\"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        base = cls.configurable_base()\n        return (base.__impl_class, base.__impl_kwargs)\n\n    @classmethod\n    def _restore_configuration(cls, saved):\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        self.name = name\n        try:\n            self.arg_pos = inspect.getargspec(func).args.index(self.name)\n        except ValueError:\n            # Not a positional parameter\n            self.arg_pos = None\n\n    def get_old_value(self, args, kwargs, default=None):\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        \"\"\"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    \"\"\"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    \"\"\"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 = array.array(\"B\", mask)\n    unmasked = array.array(\"B\", data)\n    for i in xrange(len(data)):\n        unmasked[i] = unmasked[i] ^ mask[i % 4]\n    if hasattr(unmasked, 'tobytes'):\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.tobytes()\n    else:\n        return unmasked.tostring()\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, with_statement\n\nimport array\nimport inspect\nimport os\nimport sys\nimport zlib\n\n\ntry:\n    xrange  # py2\nexcept NameError:\n    xrange = range  # py3\n\n\nclass ObjectDict(dict):\n    \"\"\"Makes a dictionary behave like an object, with attribute-style access.\n    \"\"\"\n    def __getattr__(self, name):\n        try:\n            return self[name]\n        except KeyError:\n            raise AttributeError(name)\n\n    def __setattr__(self, name, value):\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        \"\"\"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        \"\"\"Returns the unconsumed portion left over\n        \"\"\"\n        return self.decompressobj.unconsumed_tail\n\n    def flush(self):\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\n# Fake unicode literal support:  Python 3.2 doesn't have the u'' marker for\n# literal strings, and alternative solutions like \"from __future__ import\n# unicode_literals\" have other problems (see PEP 414).  u() can be applied\n# to ascii strings that include \\u escapes (but they must not contain\n# literal non-ascii characters).\nif not isinstance(b'', type('')):\n    def u(s):\n        return s\n    unicode_type = str\n    basestring_type = str\nelse:\n    def u(s):\n        return s.decode('unicode_escape')\n    # These names don't exist in py3, so use noqa comments to disable\n    # warnings in flake8.\n    unicode_type = unicode  # noqa\n    basestring_type = basestring  # noqa\n\n\ndef import_object(name):\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 isinstance(name, unicode_type) and str is not unicode_type:\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# Deprecated alias that was used before we dropped py25 support.\n# Left here in case anyone outside Tornado is using it.\nbytes_type = bytes\n\nif sys.version_info > (3,):\n    exec(\"\"\"\ndef raise_exc_info(exc_info):\n    raise exc_info[1].with_traceback(exc_info[2])\n\ndef exec_in(code, glob, loc=None):\n    if isinstance(code, str):\n        code = compile(code, '<string>', 'exec', dont_inherit=True)\n    exec(code, glob, loc)\n\"\"\")\nelse:\n    exec(\"\"\"\ndef raise_exc_info(exc_info):\n    raise exc_info[0], exc_info[1], exc_info[2]\n\ndef exec_in(code, glob, loc=None):\n    if isinstance(code, basestring):\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 in glob, loc\n\"\"\")\n\n\ndef errno_from_exception(e):\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\n    elif e.args:\n        return e.args[0]\n    else:\n        return None\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\n    __impl_kwargs = None\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        \"\"\"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        \"\"\"Returns the implementation class to be used if none is configured.\"\"\"\n        raise NotImplementedError()\n\n    def initialize(self):\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        \"\"\"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, (unicode_type, bytes)):\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        \"\"\"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        base = cls.configurable_base()\n        return (base.__impl_class, base.__impl_kwargs)\n\n    @classmethod\n    def _restore_configuration(cls, saved):\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        self.name = name\n        try:\n            self.arg_pos = inspect.getargspec(func).args.index(self.name)\n        except ValueError:\n            # Not a positional parameter\n            self.arg_pos = None\n\n    def get_old_value(self, args, kwargs, default=None):\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        \"\"\"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    \"\"\"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    \"\"\"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 = array.array(\"B\", mask)\n    unmasked = array.array(\"B\", data)\n    for i in xrange(len(data)):\n        unmasked[i] = unmasked[i] ^ mask[i % 4]\n    if hasattr(unmasked, 'tobytes'):\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.tobytes()\n    else:\n        return unmasked.tostring()\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": "d943ce2b",
                "new_commit_hash": "606ced19",
                "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": 198,
                            "length": 21
                        },
                        "new_range": {
                            "start": 198,
                            "length": 21
                        },
                        "section": "class Configurable(object):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    __impl_class = None",
                                "type": "context"
                            },
                            {
                                "content": "    __impl_kwargs = None",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def __new__(cls, **kwargs):",
                                "type": "deleted"
                            },
                            {
                                "content": "    def __new__(cls, *args, **kwargs):",
                                "type": "added"
                            },
                            {
                                "content": "        base = cls.configurable_base()",
                                "type": "context"
                            },
                            {
                                "content": "        args = {}",
                                "type": "deleted"
                            },
                            {
                                "content": "        init_kwargs = {}",
                                "type": "added"
                            },
                            {
                                "content": "        if cls is base:",
                                "type": "context"
                            },
                            {
                                "content": "            impl = cls.configured_class()",
                                "type": "context"
                            },
                            {
                                "content": "            if base.__impl_kwargs:",
                                "type": "context"
                            },
                            {
                                "content": "                args.update(base.__impl_kwargs)",
                                "type": "deleted"
                            },
                            {
                                "content": "                init_kwargs.update(base.__impl_kwargs)",
                                "type": "added"
                            },
                            {
                                "content": "        else:",
                                "type": "context"
                            },
                            {
                                "content": "            impl = cls",
                                "type": "context"
                            },
                            {
                                "content": "        args.update(kwargs)",
                                "type": "deleted"
                            },
                            {
                                "content": "        init_kwargs.update(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"
                            },
                            {
                                "content": "        # here too.",
                                "type": "context"
                            },
                            {
                                "content": "        instance.initialize(**args)",
                                "type": "deleted"
                            },
                            {
                                "content": "        instance.initialize(*args, **init_kwargs)",
                                "type": "added"
                            },
                            {
                                "content": "        return instance",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    @classmethod",
                                "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\n    __impl_kwargs = None\n\n    def __new__(cls, **kwargs):\n        base = cls.configurable_base()\n        args = {}\n        if cls is base:\n            impl = cls.configured_class()\n            if base.__impl_kwargs:\n                args.update(base.__impl_kwargs)\n        else:\n            impl = cls\n        args.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)\n        return instance\n\n    @classmethod\n    def configurable_base(cls):\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        \"\"\"Returns the implementation class to be used if none is configured.\"\"\"\n        raise NotImplementedError()\n\n    def initialize(self):\n        \"\"\"Initialize a `Configurable` subclass instance.\n\n        Configurable classes should use `initialize` instead of ``__init__``.\n        \"\"\"\n\n    @classmethod\n    def configure(cls, impl, **kwargs):\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, (unicode_type, bytes)):\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        \"\"\"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        base = cls.configurable_base()\n        return (base.__impl_class, base.__impl_kwargs)\n\n    @classmethod\n    def _restore_configuration(cls, saved):\n        base = cls.configurable_base()\n        base.__impl_class = saved[0]\n        base.__impl_kwargs = saved[1]",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 201,
                            "end_lineno": 216,
                            "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\n    __impl_kwargs = None\n\n    def __new__(cls, **kwargs):\n        base = cls.configurable_base()\n        args = {}\n        if cls is base:\n            impl = cls.configured_class()\n            if base.__impl_kwargs:\n                args.update(base.__impl_kwargs)\n        else:\n            impl = cls\n        args.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)\n        return instance\n\n    @classmethod\n    def configurable_base(cls):\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        \"\"\"Returns the implementation class to be used if none is configured.\"\"\"\n        raise NotImplementedError()\n\n    def initialize(self):\n        \"\"\"Initialize a `Configurable` subclass instance.\n\n        Configurable classes should use `initialize` instead of ``__init__``.\n        \"\"\"\n\n    @classmethod\n    def configure(cls, impl, **kwargs):\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, (unicode_type, bytes)):\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        \"\"\"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        base = cls.configurable_base()\n        return (base.__impl_class, base.__impl_kwargs)\n\n    @classmethod\n    def _restore_configuration(cls, saved):\n        base = cls.configurable_base()\n        base.__impl_class = saved[0]\n        base.__impl_kwargs = saved[1]",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 178,
                                "end_lineno": 271,
                                "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\n    __impl_kwargs = None\n\n    def __new__(cls, **kwargs):\n        base = cls.configurable_base()\n        args = {}\n        if cls is base:\n            impl = cls.configured_class()\n            if base.__impl_kwargs:\n                args.update(base.__impl_kwargs)\n        else:\n            impl = cls\n        args.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)\n        return instance\n\n    @classmethod\n    def configurable_base(cls):\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        \"\"\"Returns the implementation class to be used if none is configured.\"\"\"\n        raise NotImplementedError()\n\n    def initialize(self):\n        \"\"\"Initialize a `Configurable` subclass instance.\n\n        Configurable classes should use `initialize` instead of ``__init__``.\n        \"\"\"\n\n    @classmethod\n    def configure(cls, impl, **kwargs):\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, (unicode_type, bytes)):\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        \"\"\"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        base = cls.configurable_base()\n        return (base.__impl_class, base.__impl_kwargs)\n\n    @classmethod\n    def _restore_configuration(cls, saved):\n        base = cls.configurable_base()\n        base.__impl_class = saved[0]\n        base.__impl_kwargs = saved[1]",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 178,
                            "end_lineno": 271,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 233,
                            "length": 6
                        },
                        "new_range": {
                            "start": 233,
                            "length": 9
                        },
                        "section": "class Configurable(object):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        \"\"\"Initialize a `Configurable` subclass instance.",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        Configurable classes should use `initialize` instead of ``__init__``.",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        .. versionchanged:: 4.2",
                                "type": "added"
                            },
                            {
                                "content": "           Now accepts positional arguments in addition to keyword arguments.",
                                "type": "added"
                            },
                            {
                                "content": "        \"\"\"",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    @classmethod",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "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\n    __impl_kwargs = None\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        \"\"\"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        \"\"\"Returns the implementation class to be used if none is configured.\"\"\"\n        raise NotImplementedError()\n\n    def initialize(self):\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        \"\"\"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, (unicode_type, bytes)):\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        \"\"\"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        base = cls.configurable_base()\n        return (base.__impl_class, base.__impl_kwargs)\n\n    @classmethod\n    def _restore_configuration(cls, saved):\n        base = cls.configurable_base()\n        base.__impl_class = saved[0]\n        base.__impl_kwargs = saved[1]",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 178,
                            "end_lineno": 274,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/util.py",
                            "type": "method",
                            "name": "Configurable.initialize",
                            "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\n    __impl_kwargs = None\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        \"\"\"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        \"\"\"Returns the implementation class to be used if none is configured.\"\"\"\n        raise NotImplementedError()\n\n    def initialize(self):\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        \"\"\"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, (unicode_type, bytes)):\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        \"\"\"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        base = cls.configurable_base()\n        return (base.__impl_class, base.__impl_kwargs)\n\n    @classmethod\n    def _restore_configuration(cls, saved):\n        base = cls.configurable_base()\n        base.__impl_class = saved[0]\n        base.__impl_kwargs = saved[1]",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 232,
                            "end_lineno": 239,
                            "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\n    __impl_kwargs = None\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        \"\"\"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        \"\"\"Returns the implementation class to be used if none is configured.\"\"\"\n        raise NotImplementedError()\n\n    def initialize(self):\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        \"\"\"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, (unicode_type, bytes)):\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        \"\"\"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        base = cls.configurable_base()\n        return (base.__impl_class, base.__impl_kwargs)\n\n    @classmethod\n    def _restore_configuration(cls, saved):\n        base = cls.configurable_base()\n        base.__impl_class = saved[0]\n        base.__impl_kwargs = saved[1]",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 178,
                                "end_lineno": 274,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "00703240498a106fa9bee24cf01777e6647804f3^",
    "new_commit_hash": "00703240498a106fa9bee24cf01777e6647804f3",
    "commit_message": "Support positional arguments to Configurable.initialize.",
    "commit_date": "2015-03-08T19:05:11-04:00",
    "metadata": {}
}
{
    "repo_name": "tornado",
    "new_commit_hash": "00703240498a106fa9bee24cf01777e6647804f3",
    "test_file_codes": [
        "# coding: utf-8\nfrom __future__ import absolute_import, division, print_function, with_statement\nimport sys\nimport datetime\n\nimport tornado.escape\nfrom tornado.escape import utf8\nfrom tornado.util import raise_exc_info, Configurable, u, exec_in, ArgReplacer, timedelta_to_seconds, import_object\nfrom tornado.test.util import unittest\n\ntry:\n    from cStringIO import StringIO  # py2\nexcept ImportError:\n    from io import StringIO  # py3\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",
        "#!/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 864ms\nPrepared 1 package in 968ms\nInstalled 1 package in 0.95ms\n + tornado==4.2.dev1 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_00703240498a106fa9bee24cf01777e6647804f3)\nResolved 29 packages in 16ms\nInstalled 29 packages in 141ms\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_00703240498a106fa9bee24cf01777e6647804f3\n...............\ncollected 15 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_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::RaiseExcInfoTest::test_two_arg_exception\nPASSED r2e_tests.test_1::TimedeltaToSecondsTest::test_timedelta_to_seconds\nPASSED r2e_tests.test_1::UnicodeLiteralTest::test_unicode_escapes\n=================== 14 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_00703240498a106fa9bee24cf01777e6647804f3\n...............\ncollected 15 items\n\n=================================== ERRORS =====================================\n__________ ConfigurableTest.test_config_args __________\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_00703240498a106fa9bee24cf01777e6647804f3/r2e_tests/test_1.py\", line 107, in test_config_args\n    obj = TestConfigurable(42, a=4)\nTypeError: __new__() takes 1 positional argument but 2 were given\n__________ ConfigurableTest.test_config_class_args __________\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_00703240498a106fa9bee24cf01777e6647804f3/r2e_tests/test_1.py\", line 123, in test_config_class_args\n    obj = TestConfigurable(42, b=6)\nTypeError: __new__() takes 1 positional argument but 2 were given\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\nERROR r2e_tests.test_1::ConfigurableTest::test_config_args\nPASSED r2e_tests.test_1::ConfigurableTest::test_config_class\nERROR r2e_tests.test_1::ConfigurableTest::test_config_class_args\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::RaiseExcInfoTest::test_two_arg_exception\nPASSED r2e_tests.test_1::TimedeltaToSecondsTest::test_timedelta_to_seconds\nPASSED r2e_tests.test_1::UnicodeLiteralTest::test_unicode_escapes\n=================== 2 errors, 12 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:** TypeError When Passing Positional Arguments to `Configurable.initialize`

**Description:**
Initializing a `Configurable` subclass with positional arguments results in a `TypeError`. The `__new__` method does not accept positional arguments, causing the initialization to fail when extra arguments are provided.

**Example Code:**
```python
obj = TestConfigurable(42, a=4)
```

**Expected Behavior:**
The `TestConfigurable` instance should be created successfully with `pos_arg` set to `42` and `a` set to `4`.

**Actual Behavior:**
A `TypeError` is raised:
```
TypeError: __new__() takes 1 positional argument but 2 were given
```

[/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, with_statement

import array
import inspect
import os
import sys
import zlib


try:
    xrange  # py2
except NameError:
    xrange = range  # py3


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

    def __setattr__(self, name, value):
        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):
        """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):
        """Returns the unconsumed portion left over
        """
        return self.decompressobj.unconsumed_tail

    def flush(self):
        """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()


# Fake unicode literal support:  Python 3.2 doesn't have the u'' marker for
# literal strings, and alternative solutions like "from __future__ import
# unicode_literals" have other problems (see PEP 414).  u() can be applied
# to ascii strings that include \u escapes (but they must not contain
# literal non-ascii characters).
if not isinstance(b'', type('')):
    def u(s):
        return s
    unicode_type = str
    basestring_type = str
else:
    def u(s):
        return s.decode('unicode_escape')
    # These names don't exist in py3, so use noqa comments to disable
    # warnings in flake8.
    unicode_type = unicode  # noqa
    basestring_type = basestring  # noqa


def import_object(name):
    """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 isinstance(name, unicode_type) and str is not unicode_type:
        # 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])


# Deprecated alias that was used before we dropped py25 support.
# Left here in case anyone outside Tornado is using it.
bytes_type = bytes

if sys.version_info > (3,):
    exec("""
def raise_exc_info(exc_info):
    raise exc_info[1].with_traceback(exc_info[2])

def exec_in(code, glob, loc=None):
    if isinstance(code, str):
        code = compile(code, '<string>', 'exec', dont_inherit=True)
    exec(code, glob, loc)
""")
else:
    exec("""
def raise_exc_info(exc_info):
    raise exc_info[0], exc_info[1], exc_info[2]

def exec_in(code, glob, loc=None):
    if isinstance(code, basestring):
        # 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 in glob, loc
""")


def errno_from_exception(e):
    """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
    elif e.args:
        return e.args[0]
    else:
        return None


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
    __impl_kwargs = None

    def __new__(cls, **kwargs):
        base = cls.configurable_base()
        args = {}
        if cls is base:
            impl = cls.configured_class()
            if base.__impl_kwargs:
                args.update(base.__impl_kwargs)
        else:
            impl = cls
        args.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)
        return instance

    @classmethod
    def configurable_base(cls):
        """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):
        """Returns the implementation class to be used if none is configured."""
        raise NotImplementedError()

    def initialize(self):
        """Initialize a `Configurable` subclass instance.

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

    @classmethod
    def configure(cls, impl, **kwargs):
        """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, (unicode_type, bytes)):
            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):
        """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):
        base = cls.configurable_base()
        return (base.__impl_class, base.__impl_kwargs)

    @classmethod
    def _restore_configuration(cls, saved):
        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):
        self.name = name
        try:
            self.arg_pos = inspect.getargspec(func).args.index(self.name)
        except ValueError:
            # Not a positional parameter
            self.arg_pos = None

    def get_old_value(self, args, kwargs, default=None):
        """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):
        """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):
    """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):
    """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 = array.array("B", mask)
    unmasked = array.array("B", data)
    for i in xrange(len(data)):
        unmasked[i] = unmasked[i] ^ mask[i % 4]
    if hasattr(unmasked, 'tobytes'):
        # 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.tobytes()
    else:
        return unmasked.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:** TypeError When Passing Positional Arguments to `Configurable.initialize`

**Description:**
Initializing a `Configurable` subclass with positional arguments results in a `TypeError`. The `__new__` method does not accept positional arguments, causing the initialization to fail when extra arguments are provided.

**Example Code:**
```python
obj = TestConfigurable(42, a=4)
```

**Expected Behavior:**
The `TestConfigurable` instance should be created successfully with `pos_arg` set to `42` and `a` set to `4`.

**Actual Behavior:**
A `TypeError` is raised:
```
TypeError: __new__() takes 1 positional argument but 2 were given
```

[/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_default": "PASSED",
    "ImportObjectTest.test_import_member": "PASSED",
    "ImportObjectTest.test_import_member_unicode": "PASSED",
    "ImportObjectTest.test_import_module": "PASSED",
    "ImportObjectTest.test_import_module_unicode": "PASSED",
    "RaiseExcInfoTest.test_two_arg_exception": "PASSED",
    "TimedeltaToSecondsTest.test_timedelta_to_seconds": "PASSED",
    "UnicodeLiteralTest.test_unicode_escapes": "PASSED"
}
diff --git a/tornado/util.py b/tornado/util.py
index d943ce2b..606ced19 100644
--- a/tornado/util.py
+++ b/tornado/util.py
@@ -198,21 +198,21 @@ class Configurable(object):
     __impl_class = None
     __impl_kwargs = None
 
-    def __new__(cls, **kwargs):
+    def __new__(cls, *args, **kwargs):
         base = cls.configurable_base()
-        args = {}
+        init_kwargs = {}
         if cls is base:
             impl = cls.configured_class()
             if base.__impl_kwargs:
-                args.update(base.__impl_kwargs)
+                init_kwargs.update(base.__impl_kwargs)
         else:
             impl = cls
-        args.update(kwargs)
+        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)
+        instance.initialize(*args, **init_kwargs)
         return instance
 
     @classmethod
@@ -233,6 +233,9 @@ class Configurable(object):
         """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
 

{"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, with_statement\n\nimport array\nimport inspect\nimport os\nimport sys\nimport zlib\n\n\ntry:\n    xrange  # py2\nexcept NameError:\n    xrange = range  # py3\n\n\nclass ObjectDict(dict):\n    \"\"\"Makes a dictionary behave like an object, with attribute-style access.\n    \"\"\"\n    def __getattr__(self, name):\n        try:\n            return self[name]\n        except KeyError:\n            raise AttributeError(name)\n\n    def __setattr__(self, name, value):\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        \"\"\"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        \"\"\"Returns the unconsumed portion left over\n        \"\"\"\n        return self.decompressobj.unconsumed_tail\n\n    def flush(self):\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\n# Fake unicode literal support:  Python 3.2 doesn't have the u'' marker for\n# literal strings, and alternative solutions like \"from __future__ import\n# unicode_literals\" have other problems (see PEP 414).  u() can be applied\n# to ascii strings that include \\u escapes (but they must not contain\n# literal non-ascii characters).\nif not isinstance(b'', type('')):\n    def u(s):\n        return s\n    unicode_type = str\n    basestring_type = str\nelse:\n    def u(s):\n        return s.decode('unicode_escape')\n    # These names don't exist in py3, so use noqa comments to disable\n    # warnings in flake8.\n    unicode_type = unicode  # noqa\n    basestring_type = basestring  # noqa\n\n\ndef import_object(name):\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 isinstance(name, unicode_type) and str is not unicode_type:\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# Deprecated alias that was used before we dropped py25 support.\n# Left here in case anyone outside Tornado is using it.\nbytes_type = bytes\n\nif sys.version_info > (3,):\n    exec(\"\"\"\ndef raise_exc_info(exc_info):\n    raise exc_info[1].with_traceback(exc_info[2])\n\ndef exec_in(code, glob, loc=None):\n    if isinstance(code, str):\n        code = compile(code, '<string>', 'exec', dont_inherit=True)\n    exec(code, glob, loc)\n\"\"\")\nelse:\n    exec(\"\"\"\ndef raise_exc_info(exc_info):\n    raise exc_info[0], exc_info[1], exc_info[2]\n\ndef exec_in(code, glob, loc=None):\n    if isinstance(code, basestring):\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 in glob, loc\n\"\"\")\n\n\ndef errno_from_exception(e):\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\n    elif e.args:\n        return e.args[0]\n    else:\n        return None\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\n    __impl_kwargs = None\n\n    def __new__(cls, **kwargs):\n        base = cls.configurable_base()\n        args = {}\n        if cls is base:\n            impl = cls.configured_class()\n            if base.__impl_kwargs:\n                args.update(base.__impl_kwargs)\n        else:\n            impl = cls\n        args.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)\n        return instance\n\n    @classmethod\n    def configurable_base(cls):\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        \"\"\"Returns the implementation class to be used if none is configured.\"\"\"\n        raise NotImplementedError()\n\n    def initialize(self):\n        \"\"\"Initialize a `Configurable` subclass instance.\n\n        Configurable classes should use `initialize` instead of ``__init__``.\n        \"\"\"\n\n    @classmethod\n    def configure(cls, impl, **kwargs):\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, (unicode_type, bytes)):\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        \"\"\"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        base = cls.configurable_base()\n        return (base.__impl_class, base.__impl_kwargs)\n\n    @classmethod\n    def _restore_configuration(cls, saved):\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        self.name = name\n        try:\n            self.arg_pos = inspect.getargspec(func).args.index(self.name)\n        except ValueError:\n            # Not a positional parameter\n            self.arg_pos = None\n\n    def get_old_value(self, args, kwargs, default=None):\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        \"\"\"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    \"\"\"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    \"\"\"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 = array.array(\"B\", mask)\n    unmasked = array.array(\"B\", data)\n    for i in xrange(len(data)):\n        unmasked[i] = unmasked[i] ^ mask[i % 4]\n    if hasattr(unmasked, 'tobytes'):\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.tobytes()\n    else:\n        return unmasked.tostring()\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:** TypeError When Passing Positional Arguments to `Configurable.initialize`

**Description:**
Initializing a `Configurable` subclass with positional arguments results in a `TypeError`. The `__new__` method does not accept positional arguments, causing the initialization to fail when extra arguments are provided.

**Example Code:**
```python
obj = TestConfigurable(42, a=4)
```

**Expected Behavior:**
The `TestConfigurable` instance should be created successfully with `pos_arg` set to `42` and `a` set to `4`.

**Actual Behavior:**
A `TypeError` is raised:
```
TypeError: __new__() takes 1 positional argument but 2 were given
```

[/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, with_statement

import array
import inspect
import os
import sys
import zlib


try:
    xrange  # py2
except NameError:
    xrange = range  # py3


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

    def __setattr__(self, name, value):
        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):
        """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):
        """Returns the unconsumed portion left over
        """
        return self.decompressobj.unconsumed_tail

    def flush(self):
        """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()


# Fake unicode literal support:  Python 3.2 doesn't have the u'' marker for
# literal strings, and alternative solutions like "from __future__ import
# unicode_literals" have other problems (see PEP 414).  u() can be applied
# to ascii strings that include \u escapes (but they must not contain
# literal non-ascii characters).
if not isinstance(b'', type('')):
    def u(s):
        return s
    unicode_type = str
    basestring_type = str
else:
    def u(s):
        return s.decode('unicode_escape')
    # These names don't exist in py3, so use noqa comments to disable
    # warnings in flake8.
    unicode_type = unicode  # noqa
    basestring_type = basestring  # noqa


def import_object(name):
    """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 isinstance(name, unicode_type) and str is not unicode_type:
        # 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])


# Deprecated alias that was used before we dropped py25 support.
# Left here in case anyone outside Tornado is using it.
bytes_type = bytes

if sys.version_info > (3,):
    exec("""
def raise_exc_info(exc_info):
    raise exc_info[1].with_traceback(exc_info[2])

def exec_in(code, glob, loc=None):
    if isinstance(code, str):
        code = compile(code, '<string>', 'exec', dont_inherit=True)
    exec(code, glob, loc)
""")
else:
    exec("""
def raise_exc_info(exc_info):
    raise exc_info[0], exc_info[1], exc_info[2]

def exec_in(code, glob, loc=None):
    if isinstance(code, basestring):
        # 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 in glob, loc
""")


def errno_from_exception(e):
    """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
    elif e.args:
        return e.args[0]
    else:
        return None


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
    __impl_kwargs = None

    def __new__(cls, **kwargs):
        base = cls.configurable_base()
        args = {}
        if cls is base:
            impl = cls.configured_class()
            if base.__impl_kwargs:
                args.update(base.__impl_kwargs)
        else:
            impl = cls
        args.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)
        return instance

    @classmethod
    def configurable_base(cls):
        """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):
        """Returns the implementation class to be used if none is configured."""
        raise NotImplementedError()

    def initialize(self):
        """Initialize a `Configurable` subclass instance.

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

    @classmethod
    def configure(cls, impl, **kwargs):
        """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, (unicode_type, bytes)):
            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):
        """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):
        base = cls.configurable_base()
        return (base.__impl_class, base.__impl_kwargs)

    @classmethod
    def _restore_configuration(cls, saved):
        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):
        self.name = name
        try:
            self.arg_pos = inspect.getargspec(func).args.index(self.name)
        except ValueError:
            # Not a positional parameter
            self.arg_pos = None

    def get_old_value(self, args, kwargs, default=None):
        """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):
        """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):
    """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):
    """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 = array.array("B", mask)
    unmasked = array.array("B", data)
    for i in xrange(len(data)):
        unmasked[i] = unmasked[i] ^ mask[i % 4]
    if hasattr(unmasked, 'tobytes'):
        # 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.tobytes()
    else:
        return unmasked.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